I'm trying to display a Chart.js graph inside a <canvas>
, and this canvas is wrapped inside a <div>
.
I want the graph to be responsive, have a fixed height of 700px and a width of 80% of the page's width. On top of all, I want this graph to be centered inside the page ! My code is below
HTML
<div class='chartContainer'>
<canvas id="canvas"></canvas>
</div>
CSS
.chartContainer{
text-align: center;
}
canvas{
width: 80% !important;
height: 700px !important;
margin: 0;
}
JAVASCRIPT
new Chart(canvasContext, {
type: 'line',
data: {
labels: hourLabels,
datasets: dataToRender
},
options: {
responsive: true,
maintainAspectRatio: false
});
My problem is : I can't center it, the <div>
takes the whole page but the <canvas>
seems to have a margin applied to it even though it doesn't appear inside the DOM console...
Screenshot of the apparent margin
Can anyone point my problem ? Thank you very much :-)
col-md-6 , and you want everything inside of . topleft to be centered. If that is the case, then give . topleft the tags text-align:center; to set its contents to be centered, and float:left; to keep .
Luckily, Chart. js does most of this complex work for us! A Chart. js chart is responsive by default, but with one limitation: it maintains its aspect ratio.
Use "display:block;margin:0 auto;" to center the div containing the JS table. Show activity on this post. Make a container for your canvas and give it display: inline-block style. Then you can treat the container like any html block.
Chart. js charts are rendered on user provided canvas elements. Thus, it is up to the user to create the canvas element in a way that is accessible. The canvas element has support in all browsers and will render on screen but the canvas content will not be accessible to screen readers.
Put this in your CSS
canvas{
margin: 0 auto;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With