Praneet Dixit
Praneet Dixit

Reputation: 1425

Set size of div using javascript

I have a div with id="test" What I am trying to do is to resize the div to body.clientHeight-80px . So that the height of the element fills all the visible space on a browser window (without scrolling) except the 80px high header. I have js code as below:

let Height = document.body.clientHeight-80;
let myElement = document.getElementById("test");
myElement.style.height = Height;

The code will work fine if I use something like :myElement.style.height = "600px";. I think the problem is that document.body.clientHeight; is returning a value without the unit px.

Upvotes: 2

Views: 186

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

Concatenate "px"

myElement.style.height = Height + "px";  

and PS: use const, not let. Also preferably, if Height is not a Function that returns Methods (or a Class) use it as lowercase height.

Use CSS, not JS

#test{
   height: calc(100vh - 80px);
}

if 100vh (Viewport Height) was your intention.

Example:

/*QuickReset*/*{margin:0; box-sizing:border-box;}

:root {
  --height-head: 80px;
}

#head {
  height: var(--height-head);
  background: #eee;
  position: sticky;
  top: 0;
  z-index: 1000;
}

#test {
  height: calc(100vh - var(--height-head));
  background: #0bf;
}

#main {
  min-height: 60vh;
  background: #aaa;
}
#foot {
  min-height: 20vh;
  background: #444;
  color: #fff;
}
<header id="head">HEADER</header>
<div id="test">GALLERY calc(100vh - 80px)</div>
<main id="main">MAIN</main>
<footer id="foot">FOOTER</footer>

Upvotes: 3

Related Questions