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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *