-1

If you have an html document that goes like this:

<body>
  <div id="top"></div>
  <div id="rest"></div>
</body>

and I give the "top" div a height of 40px, is there a way to give "rest" div the rest of the height of the body in css. I know it's possible in Javascript like this

function derest(){
var bodyheight = window.getComputedStyle(document.getElementsByTagName('body')[0], null).height;

bodyheight = bodyheight.substring(0, bodyheight.length - 2);

var topheight = window.getComputedStyle(document.getElementById('top'), null).height;

topheight = topheight.substring(0, topheight.length - 2);

restheight = bodyheight - topheight;

document.getElementById("rest").style.height = restheight;

}

but this takes a lot of time, so is there a better way to do this?

Ehsan
  • 12,231
  • 3
  • 23
  • 42
JFugger_jr
  • 303
  • 1
  • 4
  • 12

4 Answers4

1

You could just use pure CSS

#top{
  height:40px;
  background:green;
}
#rest{
  height:calc(100% - 40px);
  background:red;
}
body,html{
  height:100%;
  margin:0;
  padding:0;
}
0

You can use flex to allow the #rest to stretch to fill the height:

html {
  height: 100%;
  margin:0;
  padding:0;
}
body {
  height: 100%;
  margin:0;
  padding:0;
  display: flex;
  flex-direction: column
}
#top {
  height: 40px;
  background: red;
}
#rest {
  flex: 1 1 auto;
  background: blue;
}
<div id="top"></div>
<div id="rest"></div>
Sam Willis
  • 3,751
  • 6
  • 36
  • 56
0

If the container is display: flex then you can set an element to grow (with flex-grow) to fill the remaining space.

html,
body {
  min-height: 100vh;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  flex-direction: column;
}

header {
  background-color: #aaf;
}

main {
  background-color: #afa;
  flex: 1 0 auto;
}

footer {
  background-color: #faa;
}
<header>
  Header
</header>
<main>
  Main
</main>
<footer>
  Footer
</footer>
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
-1

You can use:

#top {
 position: fixed;
 left: 0px;
 top: 0px;
 width: 100%;
 height: 40px;
}

#rest {
 position: fixed;
 top: 40px;
 left: 0px;
 width: 100%;
 height: calc(100% - 40px);
}

or even use padding-top 40px instead of doing fixed the #rest div

https://jsfiddle.net/lonking/L5mwd6r5/

Diego N.
  • 547
  • 3
  • 7