Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get size of content box

Tags:

javascript

dom

I was using padding to restrict the size of the content-box. I need a way to get the size of the content box width and hight in pixels.

I'm open to work around's like nesting elements, pseudo-elements, trying out something like flex box setups.

However, a vanilla JavaScript way to get these values is the subject of the question.

Example: http://codepen.io/anon/pen/lbzJi

like image 708
ThorSummoner Avatar asked Jul 19 '26 18:07

ThorSummoner


1 Answers

Taken from the answer to a similar question; you can use window.getComputedStyle(element, null).getPropertyValue('css-property'); to obtain the value of a computed CSS property. In your case, you can use this for the properties padding-left, padding-right, padding-top and padding-bottom.

For example, to compute the height of the content box of your "box" div you can do something similar to the following where I assume the padding is specified as an integer (hence the parseInt);

function property(e, p) { 
    return parseInt(window.getComputedStyle(e, null).getPropertyValue(p)); 
}

var box = document.getElementById('box');
var paddingTop = property(box, 'padding-top');
var paddingBottom = property(box, 'padding-bottom');    
var contentHeight = box.clientHeight - paddingTop - paddingBottom;
like image 126
Daniël Knippers Avatar answered Jul 21 '26 08:07

Daniël Knippers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!