Skip to content Skip to sidebar Skip to footer

Why Doesn't The Nested Flex Parent Height Grow With Children?

In this codepen the children overflow the parent height but why does the flex parent height not grow with children? I can use display:block to achieve it, but I would want it to be

Solution 1:

This is the logical behavior and its how the algorithm of flexbox works. To start, let's remove some properties especially the flex-shrink:0.

html,body{
  height:100%;
  margin:0;
}
.grand-parent{
  height:100%;
  overflow:auto;
  display:flex;
}
.parent{
  display:flex;
  flex-direction:column;
  min-height:100%;
  width:100%;
}

.child{
  height:1500px;
  width:100%;
  display:flex;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<divclass="grand-parent"><divclass="parent"><divclass="child green"></div><divclass="child blue"></div></div></div>

As we can clearly see, we have no overflow because the algorithm will shrink the elements to fit their parent container.


Initially we have defined the html,body to be height:100% (it's ok) then we defined the grand-parent to be height:100% and a flex container with a row direction (it's ok). Then we made .parent element to be min-height:100% and since its a flex item its height will be equal to the height of its parent because the alignment is set by default to stretch (so min-height:100% is somehow useless in this case). We have also made the parent element to be a flex container with a column direction.

Now, let's consider the child elements. Their total height will exceed the height of their parent so they will shrink equally to fit inside it as this is the default behavior AND the parent will not grow with them even if you define flex-shrink:0 on it because there is nothing to shrink for the parent element simply because its following a row direction inside his flex container and there is no width overflowing.

If you add flex-shrink:0 to child they won't srink AND they will overflow their parent but will not force their parent to grow with them because the height of the parent is defined within its own flex container by the stretch behavior.

Now if you change the alignment of the grand-parent element, the parent element will grow because its height will now be defined with the height of its content and not the stretch behavior and you will also notice that flex-shrink:0 will do nothing on the child elements:

html,body{
  height:100%;
  margin:0;
}
.grand-parent{
  height:100%;
  overflow:auto;
  display:flex;
  align-items:flex-start;
}
.parent{
  display:flex;
  flex-direction:column;
  min-height:100%;
  width:100%;
}

.child{
  height:1500px;
  width:100%;
  display:flex;
  flex-shrink:0;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<divclass="grand-parent"><divclass="parent"><divclass="child green"></div><divclass="child blue"></div></div></div>

Post a Comment for "Why Doesn't The Nested Flex Parent Height Grow With Children?"