Tien Yuan Tien Yuan - 3 months ago 15
CSS Question

CSS way to adjust a div's height based on another div

I have a div that contains a flexible-area, popup-area and a footer.


  • Flexible-area and footer are always present.

  • Popup-area is 0, 40px, or 60px, since its contents are
    dynamically changed with js.

  • Flexible-area should fill all the space above the footer.



Is there a css-only method to allow the flexible-area to increase/decrease its height based on the size of the popup?

With the current css I have, when I delete the popup in the jsfiddle, flexible does not expand to fill the area.

I'm trying to see if I can do this without jquery or flexbox for max compatibility.

Thanks for your suggestions/comments!

https://jsfiddle.net/L8me7fLk/



div {
color: #ffffff;
}
#container {
height: 100vh;
width: 100vw;
}
#flexible {
background-color: red;
width: 100vw;
min-height: 68vh;
max-height: 80vh;
}
#popup {
width: 90%;
max-height: 60px;
min-height: 40px;
line-height: 20px;
overflow-y: scroll;
position: absolute;
bottom: 0;
margin-bottom: 50px;
background-color: #cccccc;
}
#footer {
width: 90%;
height: 50px;
background-color: #666666;
position: absolute;
bottom: 0;
}

<div id="container">
<div id="flexible">
1content
<br/>2content
<br/>3content
<br/>
</div>
<div id="popup">
1popup
<br/>2popup
<br/>3popup
<br/>4popup
<br/>5popup
<br/>
</div>
<div id="footer">
footer
</div>
</div>




Answer

The desired result can be achieved with flexbox.

Firstly, it is a good idea to eliminate <br/>s from the code. You can place these items in <div>s instead.

...
<div>1content</div>
<div>2content</div>
<div>3content</div>
...

On the container, you can use flexbox to tell it to behave as a column:

#container {
  display: flex;
  flex-flow: column wrap;
}

This will similarly be required for the children, because the layout of contents of flexible, popup, and footer are columns.

Now the most important part. The flexbile div should take up the available space, while the div underneath it should not. Therefore, we can apply the following:

#flexible {
  display: flex;
  flex: 1 0 auto;
}

#popup {
  display: flex;
  flex: 0 1 auto;
}

This tells flexible to use available space, and popup not to. For more information on how the flex selector works, see https://developer.mozilla.org/en/docs/Web/CSS/flex

JS Fiddle example