Skip to content Skip to sidebar Skip to footer

How To Guarantee An Element Will Have A Particular Height

Say that I have this element on my page:
 
I want to use JavaScript to measure the height of the div to figure out how many px

Solution 1:

Set the font-style: 1em !important; on the element, and get the font size in px using Window#getComputedStyle:

var fontSize = window.getComputedStyle(div).fontSize;

console.log(fontSize);
<divid="div"style="font-size: 1em;"></div>

My previous not bullet proof answer:

This fails if the user uses borders and/or paddings which height is greater than 16.

You can use box-sizing: border-box on the element. With this box sizing, the borders and the paddings don't increase the dimensions of the element. The content area is the original width/height minus any paddings and borders.

console.log(div.getBoundingClientRect().height);
div {
  padding: 3px;
  border: 2px solid black;
}
<divid="div"style="height: 1em; box-sizing: border-box;">

Post a Comment for "How To Guarantee An Element Will Have A Particular Height"