1

I have this layout and I am trying to get the inner red child element to be scrolled instead of overflowing its parent:

overflowing child

I found a seemingly hacky way to do this - I got the layout I wanted by setting overflow-y: hidden (auto also works) on both the grandparent and on the great grandparent:

enter image description here

Here is my code (and here is a convenient jsfiddle: https://jsfiddle.net/2zw3qng7/5/):

<div id="greatgreatgrandparent">
  <div id="greatgrandparent">
    greatgrandparent
    <div id="grandparent">
      grandparent
      <div id="parent">
        parent
        <div id="child">
          <div>child</div>
          <div>child</div>
          <div>child</div>
          <div>child</div>
          <div>child</div>
          <div>child</div>
        </div>
      </div>
    </div>
    <div id="granduncle">
      granduncle
    </div>
  </div>
</div>

div {
  padding: 16px;
}

#greatgreatgrandparent {
  background: green;
  height: 300px;
  display: flex;
  flex-direction: column;
}

#greatgrandparent {
  background: greenyellow;
  flex: 1;
  display: flex;
  flex-direction: column;
  /* overflow-y: hidden; */
}

#grandparent {
  flex: 1;
  background: yellow;
  display: flex;
  flex-direction: column;
  /* overflow-y: hidden; */
}

#parent {
  flex: 1;
  background: orange;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}

#child {
  flex: 1;
  background: red;
  height: 2000px;
}

#granduncle {
  background: purple;
}

Is there a better way to achieve this? It's not intuitive to me that I need to set overflow: hidden (or auto) on the grandparent and great-grandparent nodes - I would have expected just setting overflow: scroll on the parent node would be enough to get the child to scroll and have the parent grow to fill its flex container. It's weird to me that setting overflow: hidden on an ancestor node actually affects a decedent node's height.

This is a simplified version of my actual layout which has many more flexbox nodes in the middle. It's a pain to plumb overflow: hidden through all these nodes to get my child node to scroll.

Is there a better way to do this? Or am I doing it the proper way?

Patrick Finnigan
  • 1,767
  • 16
  • 28
  • 1
    Just add `* { min-height: 0 }` to your code. https://jsfiddle.net/gh98sfjn/ – Michael Benjamin Sep 03 '21 at 19:10
  • 1
    Thanks, this works a charm. The linked "duplicate" question above explains why the default `min-height` of elements is `auto` which sizes them to their children - which was a breaking change from the previous default behavior to have `min-height: 0` and `min-width: 0`. Setting `overflow-y: hidden` on a parent works because that turns the parent into a "scroll container" and scroll containers get a default min size of 0. Spec: https://www.w3.org/TR/css-flexbox-1/#min-size-auto – Patrick Finnigan Sep 15 '21 at 21:51

0 Answers0