KevBot KevBot -4 years ago 150
HTML Question

How to make Flexbox (flex-grow) take content into account for sizing?

How can we get Flexbox to stop equalizing space in sibling elements when both of the elements are using

flex-grow: 1
. This is difficult to explain upfront, so here is the code quickly followed by example screenshots of the issue, and desired behavior.



.Parent {
display: flex;
flex-direction: column;
background-color: lightcoral;
width: 400px;
min-height: 200px;
}

.Parent>div {
flex: 1;
}

.child1 {
background-color: lightblue;
}

.child2 {
background-color: lightgreen;
}

<div class="Parent">
<div class="child1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sagittis lorem at odio euismod tincidunt. Proin aliquet velit nec augue venenatis laoreet. Etiam nec metus mi. Aliquam sit amet velit non lectus porttitor accumsan sit amet egestas risus.</div>
<div class="child2">Lorem ipsum</div>
</div>





The issue:



Notice the equal space under the content of each div.
enter image description here

Desired:



When there is little content in the children divs, the divs should be of equal height:
enter image description here

When one of the divs has a lot of content, I would expect the div with more content to only be as tall as the content (if it passes the original flex grow allotment).
enter image description here

How can I get this behavior? Seems it should be easy using Flexbox.

Answer Source

flex-basis is the property you're looking for. https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis

The flex-basis CSS property specifies the flex basis which is the initial main size of a flex item. This property determines the size of the content-box unless specified otherwise using box-sizing.

By default, flex will take into account the content in the element when computing flex-grow - to disable that, just specify flex-basis: 0

.Parent {
  display: flex;
  flex-direction: column;
  background-color: lightcoral;
  width: 400px;
  min-height: 200px;
}

.Parent>div {
  flex-grow: 1;
  flex-basis: 0;
}

.child1 {
  background-color: lightblue;
}

.child2 {
  background-color: lightgreen;
}
<div class="Parent">
  <div class="child1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sagittis lorem at odio euismod tincidunt. Proin aliquet velit nec augue venenatis laoreet. Etiam nec metus mi. Aliquam sit amet velit non lectus porttitor accumsan sit amet egestas risus. Etiam nec metus mi. Aliquam sit amet velit non lectus porttitor accumsan sit amet egestas risus </div>
  <div class="child2">Lorem ipsum</div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download