Chart.js图表无法水平排列问题排查(附代码)
Hey there! Let's troubleshoot why your charts are stacking vertically instead of sitting side by side. Here are the key issues and fixes:
1. Typo in Bootstrap Grid Class
You wrote <div class="raw"> but the correct Bootstrap container class for rows is .row. Bootstrap's grid system relies on .row to apply the proper flexbox/float styling that makes columns line up horizontally. Without it, the .col-md-2 elements will behave like regular block-level elements and stack vertically.
Fixed HTML Structure
<div class="container"> <div class="row"> <!-- Corrected from "raw" to "row" --> <!-- Chart wrapper --> <div class="col-md-2"> <canvas id="chart1"></canvas> </div> <div class="col-md-2"> <canvas id="chart2"></canvas> </div> <div class="col-md-2"> <canvas id="chart3"></canvas> </div> <div class="col-md-2"> <canvas id="chart4"></canvas> </div> </div> </div>
2. Missing Bootstrap CSS
If you haven't included Bootstrap's stylesheet in your page, the .col-md-2 and .row classes won't have any layout effect. Make sure you add Bootstrap's CSS in the <head> section of your HTML:
<head> <!-- Include Bootstrap CSS (use local file or official distribution) --> <link rel="stylesheet" href="path/to/bootstrap.min.css"> </head>
3. Optional: Check Chart Canvas Sizing
In some cases, Chart.js might set a default width on the canvas that makes it overflow the column container. To prevent this, you can add a custom style to ensure the canvas fits within its column:
canvas { max-width: 100%; height: auto; }
Full Working Example
Here's the complete code with fixes applied (plus a reusable function to avoid duplicate code):
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="path/to/bootstrap.min.css"> <style> canvas { max-width: 100%; height: auto; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-2"> <canvas id="chart1"></canvas> </div> <div class="col-md-2"> <canvas id="chart2"></canvas> </div> <div class="col-md-2"> <canvas id="chart3"></canvas> </div> <div class="col-md-2"> <canvas id="chart4"></canvas> </div> </div> </div> <script src="path/to/chart.min.js"></script> <script> // Reusable function to create charts function createChart(canvasId) { const mylabel = ["A", "B"]; const mydata = [10, 20]; const ctx = document.getElementById(canvasId); new Chart(ctx, { type: 'horizontalBar', data: { labels: mylabel, datasets: [{ label: '# of Votes', data: mydata, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)' ], borderWidth: 1, barThickness: 10 }] }, options: { scales: { xAxes: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, gridLines: { offsetGridLines: false } }] } } }); } // Initialize all charts createChart('chart1'); createChart('chart2'); createChart('chart3'); createChart('chart4'); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Nitin Sen

