CSS:子宽度的总和大于父宽度(inline-flex)

时间:2017-01-30 23:31:29

标签: css flexbox getcomputedstyle

尝试在I中设置水平滚动(使用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 :\'(');
&#13;
* {
  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;
}
&#13;
<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>
&#13;
&#13;
&#13;

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

结果非常惊人: 虽然计算出的样式给出了一个较小的宽度值,但实际上div的滚动偏差大于计算值(滚动使用另一个宽度值?),它仍然小于应该的值:can&#39; t向右间隔。

1 个答案:

答案 0 :(得分:3)

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

但是,Flex项目的最大内容大小为hypothetical main size

您可以使用group by column_id使最小内容贡献与最大内容相同。

&#13;
&#13;
whitespace: nowrap
&#13;
* {
  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;
}
&#13;
&#13;
&#13;