Make flexbox children 100% height of their parent

2019-01-01 14:34发布

I'm trying to fill the vertical space of a flex item inside a flexbox:

.container {
  height: 200px;
  width: 500px;
  display: flex;
  flex-direction: row;
}
.flex-1 {
  width: 100px;
  background-color: blue;
}
.flex-2 {
  position: relative;
  flex: 1;
  background-color: red;
}
.flex-2-child {
  height: 100%;
  width: 100%;
  background-color: green;
}
<div class="container">
  <div class="flex-1"></div>
  <div class="flex-2">
    <div class="flex-2-child"></div>
  </div>
</div>

And here's the JSFiddle

flex-2-child doesn't fill the required height except in the two cases where:

  1. flex-2 has a height of 100% (which is weird because a flex item has a 100% by default + it is buggy in Chrome)
  2. flex-2-child has a position absolute which is also inconvenient

This doesn't work in Chrome or Firefox currently.

标签: css css3 flexbox
8条回答
裙下三千臣
2楼-- · 2019-01-01 15:01

Similar to David Storey's answer, my work around is:

.flex-2
{
 align-items: stretch;
 display: flex;
}

Alternatively to align-items, you can use align-self just on the .flex-2-child item you want stretched.

查看更多
柔情千种
3楼-- · 2019-01-01 15:04

If I understand correctly, you want flex-2-child to fill the height and width of its parent, so that the red area is fully covered by the green?

If so, you just need to set flex-2 to use flexbox:

.flex-2 {
    display: flex;  
}

Then tell flex-2-child to become flexible:

.flex-2-child {    
    flex: 1;
}

See http://jsfiddle.net/2ZDuE/10/

The reason is that flex-2-child is not a flexbox item, but its parent is.

查看更多
登录 后发表回答