How to make a flex item not fill the height of the flex container?

user81993 picture user81993 · Oct 19, 2015 · Viewed 98k times · Source

As you can see in the code below, the left div inside the flex container stretches to meet the height of the right div. Is there an attribute I can set to make its height the minimum required for holding its content (like usual height: auto divs outside flex containers)?

#a {
  display: flex;
}
#a > div {
  background-color: red;
  padding: 5px;
  margin: 2px;
}
#b {
  height: auto;
}
<div id="a">
  <div id="b">left</div>
  <div>right<br>right<br>right<br>right<br>right<br></div>
</div>

Answer

Sebastian Wozny picture Sebastian Wozny · Oct 19, 2015

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

#a {
  display:flex;

  align-items:flex-start;
  align-content:flex-start;
  }

#a > div {
  
  background-color:red;
  padding:5px;
  margin:2px;
  }
 #a > #c {
  align-self:stretch;
 }
<div id="a">
  
  <div id="b">left</div>
  <div id="c">middle</div>
  <div>right<br>right<br>right<br>right<br>right<br></div>
  
</div>

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.