我正在尝试将Chart.js条形图居中,其中高度和宽度基于视口。
documentation明确指出以下方法不适用于<canvas style="margin: 0 auto;">
。事实上,它使图形不断缩小,越来越小。
下面是我的代码:
HTML:
<div class="chart-container">
<canvas id="myChart"</canvas>
</div>
CSS:
.chart-container {
position: relative;
margin: 0 auto;
height: 70vh;
width: 90vw;
}
Javascript:有一段Javascript代码,它获取元素并在in中创建一个new Chart
。简化如下:
const element = document.getElementById('myChart');
new Chart(element, {
type: 'bar',
data: {
labels: ['one', 'two', 'three'],
datasets: [{
label: 'Alpha',
data: [1, 2, 3]
}]
}
});
我想父容器是相同的画布垂直大小(以避免在我的网页添加不必要的缓冲区)。
You can see here that as the screen becomes too wide and the height-based sizing takes effect, the chart is shoved to the left side of the chart-container
You can see here that as the screen becomes too long and the width-based sizing takes effect, the chart-container pushes down the next element, creating a large space gap
1条答案
按热度按时间xdyibdwo1#
最后我使用了一些Javascript:
然后在我的CSS中,我删除了高度和宽度规范: