Marco Marco - 8 months ago 24
CSS Question

How to make a div take the remaining height without knowing the height?

I have 2 elements inside .container, that is .header and .overflowElem.

I want .overflowElem to take the remaining height of the .container, and it should be overflow-y: auto.


<div class="box">

<div class="container">

<div class="header">

<div class="overflowElem">
<li><a href="#">ITEM 1</a></li>
<li><a href="#">ITEM 2</a></li>
<li><a href="#">ITEM 3</a></li>



All of this HTML is injected using jQuery's ajax, like so:

type: "GET",
url: "include/get_list.php",
data: params
}).done(function(data) {
var container = $("<div></div>")
.attr("class", "container")

}).fail(function() {

}).always(function(data) {


Notice how var container is hidden at the time of initialization

CSS : {
width: 700px;
border: 1px solid red;
padding: 45px 20px 20px;

div.container {
height: 500px;
background-color: #bbb;

div.header {
background-color: red;
/* HEIGHT in pixels is UNKNOWN */

div.overflowElem {
overflow-y: auto;
CANNOT USE THIS BECAUSE i DON'T know the height of .header
height: calc(100% - height of .header in pixels);*/


Now, i could add a height to .header and calculate the height of .overflowElem using calc() and bingo!

BUT, because all of the HTML is inserted using jQuery's ajax, and it's hidden at the moment of initialization, i don't tknowthe height neither i cant get it using ajax because the container is hidden

So, what is the solution? Any ideas, tips, tricks, hacks...


Using flexbox all you have to do is update your div.container rule (without prefixing, for brevity).

div.container {
  height: 500px;
  background-color: #bbb;

  // add these properties here
  display: flex;
  flex-direction: column;

Granted, this is assuming your browser support allows you to use flexbox. CSS Tricks has a great write-up of flexbox here.