在flexbox列子上高度100%

时间:2014-01-06 21:28:53

标签: css google-chrome height percentage flexbox

我在使用flexbox列时遇到麻烦,因为flex'd元素的子元素不会以百分比形式响应height。我只在Chrome中检查过此内容,据我所知,这只是Chrome的问题。这是我的例子:

HTML

<div class='flexbox'>
  <div class='flex'>
    <div class='flex-child'></div>
  </div>
  <div class='static'></div>
</div>

CSS

.flexbox{
  position:absolute;
  background:black;
  width:100%;
  height:100%;

  display: flex;
  flex-direction:column;
}

.flex{
  background:blue;
  flex:1;
}

.flex-child{
  background:red;
  height:100%;
  width:100%;
  display:block;
}

.static{
  background:green;
  width:100%;
  height:5rem;
}

Here's the CodePen.

我想要它,所以红色.flex-child填充蓝色.flex。为什么height:100%无效?

1 个答案:

答案 0 :(得分:107)

TL; DR:.flex设置为display:flex,并取消height:100%上的.flex-childYou can see the modified CodePen here.

为什么会这样:

我从this similar question了解到,根据flexbox规范,align-self:stretch值(flex'd元素的默认值)仅更改了使用的值 element的交叉大小属性(在本例中为height)。但是,百分比是根据父级的交叉大小属性的指定值计算的,而不是它的使用值。如果您破解了Inspector并在“样式”下看到height:100%,但在“已计算”下看到height:1200px,那么它会显示指定的已使用分别为。

Chrome似乎在这方面遵循规范。这意味着在height:100%上设置.flex-child表示height的指定.flex的100%。由于我们未在height上指定.flex,这意味着我们正在抓取默认height的100%,即auto。看看为什么布局引擎感到困惑?

.flex设置为display:flex并从height:100%移除.flex-child(以便它不会继续尝试设置auto的100%) make .flex-child填写所有.flex

如果不起作用:

如果您只尝试填充.flex中的部分内容,则无效。尝试将.flex-child设置为height:90%,因为弯曲孩子意味着它将填满所有可用空间。我认为你可以用绝对定位破解它,但这似乎也不起作用。您可以将第二个孩子添加到.flex我们称之为.spacer,并将.spacer设置为flex:1,将.flex-child设置为flex:9 (务必在flex-direction:column上设置.flex。一个黑客,但我唯一能解决它的方法。 Here's the CodePen.

希望我们不必继续依赖这一点,他们只会改变规格,以达到预期的效果。