Tom Oakley Tom Oakley - 1 month ago 12
CSS Question

Prevent a flex items height from expanding to match other flex items

I have two elements inside a container, which are being side-by-side by using flex box. On the second element (

.flexbox-2
), I am setting it's height in the CSS. However, then the first element (
.flexbox-1
) will match the height of
.flexbox-2
. How would I stop
.flexbox-1
from matching the height of
.flexbox-2
, and instead just retain its natural height?

Here is what I have so far (also available as a jsFiddle)



.container {
display: -webkit-flex;
-webkit-flex-direction: row;
}
.flexbox-1 {
-webkit-flex: 1;
border: solid 3px red;
}
.flexbox-2 {
-webkit-flex: 2;
border: solid 3px blue;
height: 200px;
margin-left: 10px;
}

<div class="container">
<div class="flexbox-1">.flexbox-1</div>
<div class="flexbox-2">.flexbox-2</div>
</div>




Answer

As long as the flex container has no height itself, you can set height: 0% on the first flex item. Because it has no height to inherit from its parent, any percentage height will cause it to collapse. It will then grow with its contents.

Example

In this example I have removed the -webkit prefix. It's only really required for Safari and the prefix can be added above the non-prefixed version. I also removed flex-direction: row as it is the default value.

.container {
  display: flex;
}
.flexbox-1 {
  flex: 1;  
  height: 0%;  
  border: solid 3px red;
}
.flexbox-2 {
  flex: 2;
  border: solid 3px blue;
  height: 200px;
  margin-left: 10px;
}
<div class="container">
  <div class="flexbox-1">.flexbox-1</div>
  <div class="flexbox-2">.flexbox-2</div>
</div>