archetypo
archetypo

Reputation: 23

How to have a flexbox grow to fill the available max-height of a div

Im trying to have multiple child elements of a flex box grow to fill the available height set by the max-height parameter, when flex-direction: column. This works intuitively with max-width and flex-direction: row allowing the elements to reflow when I resize the browser within the max-width specified. Here's some simple html which should work given my understanding of flex-box:

.child {
  background: rgb(255, 255, 255);
  border: 1px solid #999;
  font-weight: bold;
  text-align: center;
  flex-basis: 1;
}

.vertical_flexbox {
  display: flex;
  flex-direction: column;
  max-height: 200px;
}
<div class='vertical_flexbox'>
  <div class='child'>1</div>
  <div class='child'>2</div>
  <div class='child'>3</div>
</div>

Am I missing something obvious? Thanks

Upvotes: 2

Views: 8641

Answers (3)

Tyler Watts
Tyler Watts

Reputation: 193

Setting flex:1 on the child element will auto-fill the space evenly if the parent has a defined height.

.child {
  background: rgb(255, 255, 255);
  border: 1px solid #999;
  font-weight: bold;
  text-align: center;
  flex: 1;
}

.vertical_flexbox {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-height: 200px;
}
<div class='vertical_flexbox'>
  <div class='child'>1</div>
  <div class='child'>2</div>
  <div class='child'>3</div>
</div>

Upvotes: 2

Dan Knights
Dan Knights

Reputation: 8368

The flex-basis CSS property sets the initial main size of a flex item.

Without the height set, this has to be an explicit value, i.e. px, em, rem etc. For your case, you could set flex-basis on the children elements to be more than the max-height:

.child {
  background: rgb(255, 255, 255);
  border: 1px solid #999;
  font-weight: bold;
  text-align: center;
  /* 67 * 3 is > 200 */
  flex-basis: 67px;
}

.vertical_flexbox {
  display: flex;
  flex-direction: column;
  max-height: 200px;
}
<div class='vertical_flexbox'>
  <div class='child'>1</div>
  <div class='child'>2</div>
  <div class='child'>3</div>
</div>

This is if you know the exact value of max-height. If you don't, you could just set flex-basis to an enormous number as a catch-all.

Otherwise, you'd have to set the parents height explicitly, which would then allow you to set flex-basis: 100%.

Upvotes: 0

Erica T.
Erica T.

Reputation: 450

I think it has to do with the behavior of block elements such as divs, which occupy 100% of width but only the minimum height needed. If you use height:200px instead of max-height you get the display you are looking for.

Upvotes: 0

Related Questions