Box Model: Border-Box

When using border-box as the box model, the content width and height becomes automatic, but I’m wondering if there is still a way to measure the content area’s width and height. Is there a way to use JavaScript to get the content-area dimensions when using border-box?

With yourDOMelement.offsetHeight and yourDOMelement.offsetWidth you will get the real dimensions of an element – whether you used border-box or not.

If you have this style, for example:

* {
  box-sizing: border-box;
}
#your-el {
  width: 100px;
  height: 100px;
  padding: 10px;
}

you will get 100 as a result from JS:

const yourDOMelement = document.getElementById('your-el');
console.log(yourDOMelement.offsetWidth); // logs 100

With this:

* {
  box-sizing: content-box;
}
#your-el {
  width: 100px;
  height: 100px;
  padding: 10px;
}

you get 120.

Hi, @mirja_t.

So, there isn’t really a way to easily get the content area dimensions (area that excludes margin, border, and padding) in your first example? Even though I can calculate manually (content area would be 80px width and 80px height after subtracting the padding), was hoping that there would be a built-in for this.

Why don’t you get the dimensions of the content then? That would be easy.

<body>
<div id="your-el">
<div id="content">
</div>
</div>
</body>
* {
  box-sizing: border-box;
}
#your-el {
  width: 100px;
  height: 100px;
  padding: 10px;
}
const yourDOMelement = document.getElementById('content');
console.log(yourDOMelement.offsetWidth); // 80
2 Likes

@mirja_t. Ohhhh, so, using the .offsetWidth on the element object will give the content width?
Is the same for .offsetHeight?

No, but getting the offsetWidth of the child element gives you the width of parent’s content, if the parent is set to content-box. Given the parent has one child only. Same for offsetHeight.