Reputation: 63577
How can you get the dimensions of the content area of a DOM element?
Strangely couldn't find a question/answer to this. Many questions about measuring DOM elements as a whole, but none about the content area itself.
Example:
div {
width: 100px;
height: 200px;
padding: 10px;
border: 5px;
margin: 15px;
box-sizing: border-box;
}
Now somethings get you various parts of the box model, but nothing seems to give you the content:
const elem = document.querySelector('div');
elem.offsetWidth; // content + padding + border
elem.clientWidth; // content + padding
window.getComputedStyle(elem); // Returns an object with width padding and border as strings like "15px".
window.getBoundingClientRect(); // Gives width and height of total box-model excluding margin if sizing is border-box.
Upvotes: 2
Views: 294
Reputation: 31987
You'll need to subtract the computed paddings from the client width and height:
const elem = document.getElementById('elem');
const computedStyles = window.getComputedStyle(elem)
const extraWidthOffset = +computedStyles.getPropertyValue("padding-left").slice(0, -2) + +computedStyles.getPropertyValue("padding-right").slice(0, -2)
const extraHeightOffset = +computedStyles.getPropertyValue("padding-top").slice(0, -2) + +computedStyles.getPropertyValue("padding-bottom").slice(0, -2)
const contentWidth = elem.clientWidth - extraWidthOffset
const contentHeight = elem.clientWidth - extraHeightOffset
console.log(contentWidth, contentHeight)
#elem {
width: 100px;
height: 200px;
padding: 10px;
border: 5px;
margin: 15px;
box-sizing: border-box;
}
<div id="elem">
<p>Content</p>
</div>
Upvotes: 2