简体   繁体   中英

CSS - Keep children inside container

I'm trying to fit 2 children inside a container without them overflowing.
Here is an example of my issue: https://jsfiddle.net/195em81t/

I want it so that if #footer is present it will take 20% of the container and #content will fill the other 80% and add a scroll bar if necessary.

I don't want to set a hard 80% height on #content as sometimes #footer won't be present in which case I want #content to take 100% of the height;

You can use flexbox. By using flex-grow property, flex items can grow to fill remaining space.

 .container { height: 200px; width: 100px; border: 2px; border-style: solid; display: flex; flex-direction: column; } .content { flex: 80%; /* Start at 80%, then grow to fill remaining space */ overflow: auto; /* In case contents are too tall */ } .footer { flex: 20%; /* Start at 20%, then grow to fill remaining space */ overflow: auto; /* In case contents are too tall */ } 
 <div class="container"> <div class="content"> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> </div> <div class="footer"> Footer </div> </div> <hr /> <div class="container"> <div class="content"> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> Content<br> </div> </div> 

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