-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,655
  • 3
  • 25
  • 44
JFugger_jr
  • 313
  • 1
  • 4
  • 13

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
  • 4,001
  • 7
  • 40
  • 59
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
  • 914,110
  • 126
  • 1,211
  • 1,335
-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.
  • 562
  • 3
  • 10