I have this layout and I am trying to get the inner red child element to be scrolled instead of overflowing its parent:
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:
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?