Evan Graham
Evan Graham

Reputation: 398

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;

Upvotes: 0

Views: 52

Answers (1)

Oriol
Oriol

Reputation: 288020

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>

Upvotes: 3

Related Questions