Jacob Barrow
Jacob Barrow

Reputation: 701

Set div to fill the page and make it keep that height when appended too

I have 3 rows, the middle of which gets data appended to so it grows in height. How can I make the middle div fill the rest of the page height and then stay that size when more data is added to it?

This is the relevant CSS for the middle element:

#scroll {
    overflow: auto
    height: ?
}

Here's a codepen of the layout - I've fixed the middle div's height for now to get the scrolling to work, but if I use flexbox to make it fill the height it just expands when content is appended to it, making the whole page taller.


E: The header and footer can't have a fixed height because they have dynamically set text in them

Upvotes: 0

Views: 42

Answers (2)

Jacob Barrow
Jacob Barrow

Reputation: 701

After playing with CSS for a while I figured it was a bit beyond its capabilities, so since I'm using javascript anyway I wrote a quick function that calculates the height of the other elements and sets the middle one accordingly:

function addLine(height) {
  document.getElementById('scroll').innerHTML += '<p>line</p>';
}

function setHeight() {
  header = document.getElementById('header');
  footer = document.getElementById('footer');
  excess_height = header.clientHeight + footer.clientHeight;
  height = window.innerHeight - excess_height;
  document.getElementById("scroll").style.height = height + "px";
}

window.onresize = function() { 
  setHeight();
}

window.onload = function() {
  setHeight();
}
* {
  padding: 0;
  margin: 0;
}
#header, #footer {
  background: red;
  //height: 20px;
}

#scroll {
  background: green;
  text-align: center;
  height: 60px;
  overflow: auto;
}
<body>
<div id="header">
  <h1>header</h1>
</div>
<div id="scroll">
  <p>line</p>
  <p>line</p>
</div>
<div id="footer">
  <div class="add-line" onClick="addLine()">click to add line</div>
</div>

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65873

Set the header, #scroll and footer to desired heights using viewport height (vh) units that add up to 100 (100vh === 100% of the height of the viewport).

function addLine() {
  document.getElementById('scroll').innerHTML += '<p>new line</p>';
}
* {
  padding: 0;
  margin: 0;
}
.header, .footer {
  background: red;
  height:15vh;
}

#scroll {
  background: green;
  text-align: center;
  height: 70vh;
  overflow: auto;
}
<div class="header">
  <h1>header</h1>
</div>
<div id="scroll">
  <p>line</p>
  <p>line</p>
</div>
<div class="footer">
  <div class="add-line" onClick="addLine()">click to add line</div>
</div>

Upvotes: 1

Related Questions