在flexbox列子上高度100%

Cou*_*one 81 css height google-chrome 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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

这是CodePen.

我想要它,所以红色.flex-child填充蓝色.flex.为什么不起作用height:100%

Cou*_*one 112

TL; DR:设置.flexdisplay:flex,并摆脱height:100%开启.flex-child.您可以在此处查看修改过的CodePen.

为什么会这样:

我从这个类似的问题中了解到,根据flexbox规范,一个align-self:stretch值(flex'd元素的默认值)仅更改元素的交叉大小属性的使用值(在本例中height).但是,百分比是根据父级的交叉大小属性的指定值计算的,而不是它的使用值.如果你打开你的Inspector并height:100%在'Styles' height:1200px下看到但在'Computed'下,那么它分别显示指定使用的值.

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

设置.flexdisplay:flex和取出height:100%.flex-child(所以它不会继续尝试设置的100% auto),将.flex-child填补所有的.flex

如果这不起作用:

如果你试图只填充一些.flex,例如,这将无效.尝试设置.flex-childheight:90%,因为弯曲的孩子意味着它会填满所有可用空间.我认为你可以用绝对定位破解它,但这似乎也不起作用.你可以通过添加第二个孩子破解.flex,我们会打电话.spacer,并设置.spacerflex:1.flex-childflex:9(一定要设置flex-direction:column.flex也是如此).一个黑客,但我唯一能解决它的方法.这是CodePen.

希望我们不必继续依赖这个,他们只会改变规范,以更好地按照预期行事.

  • 会发生什么如果结构是深层嵌套的,那么还是必须继续应用 - "display:flex"直到最后? (8认同)