简体   繁体   中英

How to prevent an element from growing outside of its grandparent's boundaries?

I've seen a similar question answered when the element was a direct child of the container with the max-width set, but in my case, I have a div with dynamic content, and inside of it is another div, which is a growing list. I need this internal div to grow until the root div reaches its max-height , then switch to overflow.

 html, body { height: 100%; } #topDiv { background-color: lightblue; max-height: 150px; width: 100%; padding: 10px; } #insideDiv { background-color: pink; max-height: inherit; overflow-y:auto; } #anotherdiv { max-height: inherit; }
 <div id="topDiv"> <p> First paragraph </p> <div id="anotherdiv"> <div id="insideDiv"> Some inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content <br> </div> </div> <p> Final paragraph </p> </div>

You could simply add overflow-y: auto to #topDiv .

 html, body { height: 100%; } #topDiv { background-color: lightblue; max-height: 1050px; width: 100%; padding: 10px; overflow-y: auto; } #insideDiv { background-color: pink; max-height: inherit; overflow-y: auto; } #anotherdiv { max-height: inherit; }
 <div id="topDiv"> <p> First paragraph </p> <div id="anotherdiv"> <div id="insideDiv"> Some inside content <br> More inside content <br> More inside content <br> More inside content <br> More inside content </div> </div> <p> Final paragraph </p> </div>

#anotherdiv {
  max-height: 400px;
 overflow-y: auto;
}

I found a way to do this. The trick was to set display: flex on the root div and on #anotherdiv , set flex-shrink: 0 on all other children of both the root div and #anotherdiv , and finally set height: 100% and overflow-y: auto on both #anotherdiv and on the scrollable div. This does the trick. Full demo of my solution - https://codepen.io/calsal/pen/bGdgyBX .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM