为什么 children 的宽度之和大于 parent 的宽度?

Why is the sum of the children's width greater than the parent's width?

我在尝试设置水平滚动(使用 inline-flex)时遇到了以下问题:

无法在滚动条周围填充 div。试图理解为什么,似乎 children 的宽度的简单相加给出的数字(远)大于 parent.

的计算宽度

https://jsfiddle.net/jniac/vv9zhcj3/

var divs = document.querySelectorAll('.content > div');
var widths = [], sum = 0;
for (var i = 0; i < divs.length; i++) {
  var div = div = divs[i]
  // offsetWidth & getComputedStyle give (almost) the same value
  var w = div.offsetWidth;
  //var w = parseFloat(getComputedStyle(div).width);
  widths.push(w);
  sum += w;
}

console.log('div width:', widths.join(', '));
console.log('sum (including padding):', sum + 200 + 'px');
console.log('computed style:', getComputedStyle(document.querySelector('.content')).width);
console.log('...can\'t get spacing to the right :\'(');
* {
  margin:0;
  box-sizing: border-box;
  font-family: courier;
  font-size: 14px;
}
.container {
  width: 100vw;
  height: 100vh;
}
.content {
  display: inline-flex;
  height: 100%;
  padding: 100px;
}
.content > div {
  height: 100%;
  padding: 20px;
  flex: none;
}
.A { background: red; }
.B { background: blue; }
.C { background: orange; }
.inside {
  height: 100%;
  padding: 40px;
  border: rgba(255,255,255,.75) 2px dashed;
  color: white;
  font-size: 90px;
}
<div class="container">
  <div class="content">
    <div class="A"><div class="inside">AA</div></div>
    <div class="B"><div class="inside">B</div></div>
    <div class="C"><div class="inside">Long-C</div></div>
    <div class="A"><div class="inside">Quite-Long-A</div></div>
    <div class="C"><div class="inside">CC</div></div>
  </div>
</div>

var w = parseFloat(getComputedStyle(div).width); 2062px > 1684.19px

结果相当惊人: 虽然计算样式给出的宽度值很小,但实际上 div 滚动的偏移量大于计算值(滚动是否使用另一个宽度评估?),它仍然小于应有的值:可以' 得到右边的间距。

那是因为 flex 容器的大小是使用 fit-content / shrink-to-fit 算法计算的。由于它溢出,重要的是 min-content contribution of the flex items.

但是,弹性项目的大小使用 max-content 作为 hypothetical main size

您可以使用whitespace: nowrap使min-content贡献与max-content相同。

* {
  margin:0;
  box-sizing: border-box;
  font-family: courier;
  font-size: 14px;
}
.container {
  width: 100vw;
  height: 100vh;
}
.content {
  display: inline-flex;
  height: 100%;
  padding: 100px;
}
.content > div {
  height: 100%;
  padding: 20px;
  flex: none;
  white-space: nowrap;
}
.A { background: red; }
.B { background: blue; }
.C { background: orange; }
.inside {
  height: 100%;
  padding: 40px;
  border: rgba(255,255,255,.75) 2px dashed;
  color: white;
  font-size: 90px;
}
<div class="container">
  <div class="content">
    <div class="A"><div class="inside">AA</div></div>
    <div class="B"><div class="inside">B</div></div>
    <div class="C"><div class="inside">Long-C</div></div>
    <div class="A"><div class="inside">Quite-Long-A</div></div>
    <div class="C"><div class="inside">CC</div></div>
  </div>
</div>