Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js canvas : can't center it

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 :-)

like image 830
metheM Avatar asked Jan 31 '19 10:01

metheM


People also ask

How do I center a div chart?

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 .

Is Chart JS responsive?

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.

How do you move a chart in HTML?

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.

Does chart js use canvas?

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.


1 Answers

Put this in your CSS

canvas{
    margin: 0 auto;
    }
like image 109
siwakorn Avatar answered Sep 28 '22 14:09

siwakorn