Categories
JavaScript Answers

How to get the full height of a HTML element including border, padding and margin with JavaScript?

Spread the love

Sometimes, we want to get the full height of a HTML element including border, padding and margin with JavaScript.

In this article, we’ll look at how to get the full height of a HTML element including border, padding and margin with JavaScript.

How to get the full height of a HTML element including border, padding and margin with JavaScript?

To get the full height of a HTML element including border, padding and margin with JavaScript, we can use the getComputedStyle method.

For instance, we write

const el = document.querySelector("div");

let elHeight = el.offsetHeight;
elHeight += parseInt(
  window.getComputedStyle(el).getPropertyValue("margin-top")
);
elHeight += parseInt(
  window.getComputedStyle(el).getPropertyValue("margin-bottom")
);

console.log(elHeight);

to get the div with querySelector.

Then we get the height of it without the margins with offsetHeight.

Next, we call getComputedStyle with el to get the margin top and margin bottom values of the div.

And then we add them to elHeight.

Conclusion

To get the full height of a HTML element including border, padding and margin with JavaScript, we can use the getComputedStyle method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.