首页 > 解决方案 > Bootstrap > 水平扩展 ChartJS 画布以匹配溢出的列

问题描述

我在引导程序中有一个非常基本的文档,有 2 行。一个具有“n”个水平溢出的列,以及一个需要响应以匹配顶行的 n 个列的底部图表。

ChartJS 似乎使用父 div 的尺寸来使所有内容都响应,但我似乎无法使父(第二行)具有与第一行相同的宽度。有什么想法吗?谢谢。

https://jsfiddle.net/kde8u37j/

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ['', '', '', '', '', '', '', '', ''],
    datasets: [{
        label: "foo",
        data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        fill: false,
        tension: 0.3,
        datalabels: {
          align: "bottom",
          offset: 10,
        },
      },
      {
        label: "bar",
        data: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
        tension: 0.3,
        fill: "-1",
        backgroundColor: "rgba(255,193,8,0.5)",
      },
    ],
  },
});
.topParent {
  overflow-x: scroll;
  border: 1px solid red;
}

.container {
  border: 1px solid blue;
}

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.min.js"></script>

<div class='topParent'>

  <div class="container">
    <div class="row d-flex flex-nowrap">
      <div class="col col-3">
        1 of 7
      </div>
      <div class="col col-3">
        2 of 7
      </div>
      <div class="col col-3">
        3 of 7
      </div>
      <div class="col col-3">
        4 of 7
      </div>
      <div class="col col-3">
        5 of 7
      </div>
      <div class="col col-3">
        6 of 7
      </div>
      <div class="col col-3">
        7 of 7
      </div>
    </div>
    <div class="row">
      <div class="col">
        <canvas id='myChart' height='100px'></canvas>
      </div>
    </div>
  </div>
</div>

标签: csstwitter-bootstrapbootstrap-4chartschart.js

解决方案


问题不在于图表,而在于“n”列行。来自Boostrap 文档(强调我的):

使用我们强大的移动优先 flexbox 网格来构建各种形状和大小的布局,这要归功于12 列系统、6 个默认响应层、Sass 变量和 mixin 以及数十个预定义类。

你有 7 个col-3元素,加起来有 21 列。这会导致row元素扩展超出其 parent 的大小container

从每个元素中删除col-3类,以使 Bootstrap 在 parent 的范围内将它们的大小相等container


推荐阅读