htmlcss

Prevent child element from increasing parent's height which is based on flex-grow


I have a parent element with defined height (e.g. 100vh) and display: flex; flex-direction: column, and several nested child elements which don't have fixed height - their height is based on flex-grow: 1 instead. If I add a new inner-most element with a height greater that its parent then all of its ancestors' height is changed. I want the new element to overflow its parent instead of changing its height.

Here's the jsfiddle link: https://jsfiddle.net/1o8khw7z/1/

The only way to make it work is to add overflow: auto to all the elements that are in between the top parent and the new element (check CSS comments in the jsfiddle).

Bear in mind I cannot use

If there are a lot of nested elements this solution seems a bit cumbersome. Is there a better way to handle this?


Solution

  • You should be able to solve this problem by setting the fixed-height nested child element to have position: absolute (this will cause it to overflow its immediate parent).

    If you get any extra overflow that you didn't want, consider setting that immediate parent to have position: relative;. That'll prevent make measurements like width: 100%; more nicely bound to the parent.

    Updated jsfiddle!

    Notable changes:

    #grandchild {
      flex-grow: 1;
      border: 10px solid green;
      box-sizing: border-box;
      position: relative; /* new! */
    }
    
    #grandgrandchild {
      position: absolute; /* new! */
      height: 600px;
      border: 10px solid blue;
      box-sizing: border-box;
      width: 100%;
    }