Trouble getting div height with Javascript (Etch-a-Sketch project)


So I have a grid div, in which I want to create some cells. To calculate how many cells I need to fill the grid completely I need to find its width and height, I use offsetHeight and offsetWidth for this. offsetWidth works okay, but offsetHeight always returns 0.
Here’s the css:

  margin-left: 300px; /*width of the sidebar*/
  height: 100%;
  width: calc(100% - 290px);

Here’s Javascript code:

let grid = document.querySelector("#grid");
let gridHeight = grid.offsetHeight;
let gridWidth = grid.offsetWidth;

Link to GitHub repository
I tried some fixes, but without really understanding some of them, for example: adding display: block; and display: inline-block; to grid style, moving script tag to the bottom of html document, setting background-color attribute, changing height to auto, calc(100%) and calc(100% - 0px), but none of them worked. Works fine when I put a number there but that’s not what I really want here. Any help and advice would be appreciated!



Maybe one for you?


well height: 100% might very well be 0px…

but looking at the GH repo it looks like you might have figured it out?

you could try grid.getBoundingClientRect().height instead


Right now it displays a fixed number of squares so I can see how it all looks and test other stuff.

grid.getBoundingClientRect().height also returns 0 :confused:


I think the problem is setting the height via CSS, though I haven’t looked at all of your code.

Have a read of this:

If you use vh for the height in CSS, your JavaScript will start returning actual pixel heights…

  margin-left: 300px; /*width of the sidebar*/
  height: 100vh;
  width: calc(100% - 290px);
  background-color: red;


That worked! Thanks a lot!