Categories
JavaScript Answers

How to get the height of an element minus padding, margin, border widths with JavaScript?

Spread the love

Sometimes, we want to get the height of an element minus padding, margin, border widths with JavaScript.

In this article, we’ll look at how to get the height of an element minus padding, margin, border widths with JavaScript.

How to get the height of an element minus padding, margin, border widths with JavaScript?

To get the height of an element minus padding, margin, border widths with JavaScript, we get the offsetWidth and offsetHeight and subtract them by the padding and border width and height.

For instance, we write

const cs = getComputedStyle(element);

const paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
const paddingY = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);

const borderX =
  parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth);
const borderY =
  parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth);

const elementWidth = element.offsetWidth - paddingX - borderX;
const elementHeight = element.offsetHeight - paddingY - borderY;

to call getComputedStyle to get an object with the computed styles of element.

Then we get the horizontal padding with

const paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);

We get the vertical padding with parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom).

Horizontal border we get with parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth).

Vertical border we get with parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth).

Then we get the width and height without the border and padding with

const elementWidth = element.offsetWidth - paddingX - borderX;
const elementHeight = element.offsetHeight - paddingY - borderY;

Conclusion

To get the height of an element minus padding, margin, border widths with JavaScript, we get the offsetWidth and offsetHeight and subtract them by the padding and border width and height.

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.