[Chartjs]-How to move a chart.js to the center

1๐Ÿ‘

โœ…

Use "display:block;margin:0 auto;" to center the div containing the JS table.

1๐Ÿ‘

Make a container for your canvas and give it display: inline-block style. Then you can treat the container like any html block.

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
.outbox{
  text-align: center;
}
.container{
  width: 50%;
  display: inline-block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>

<div class="outbox">
  <div class="container">
    <canvas id="myChart" width="400" height="400"></canvas>
  </div>
</div>

0๐Ÿ‘

You want to center the canvas since that is where the chart is drawn on. To center the canvas see this stack article: How to center canvas in html5

Leave a comment