1

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

无法在滚动 div 周围获得填充。试图理解为什么,似乎简单地添加子项的宽度会给出一个比计算出的父项宽度大的数字(远)。

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 滚动的偏移量比计算值更大(滚动是否使用另一个宽度评估?),它仍然小于它应该是: 无法在右侧获得间距。

4

1 回答 1

3

这是因为 flex 容器是使用 fit-content / shrink-to-fit 算法调整大小的。由于它溢出,重要的是flex items 的 min-content 贡献

但是,弹性项目的大小是使用它们的 max-content 作为假设的 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>

于 2017-01-30T23:55:03.420 回答