4

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

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
  • 1
    and where is your code ? – Francois Borgies Apr 28 '14 at 07:21
  • What about `element.offsetWidth` and `element.offsetHeight` ? – Sebastien C. Apr 28 '14 at 07:22
  • This doesn't pertain to any specific code. Here is an example: http://codepen.io/anon/pen/lbzJi – ThorSummoner Apr 28 '14 at 07:26
  • 1
    From [this answer](http://stackoverflow.com/questions/5227909/get-element-padding-value-using-javascript), you can do `window.getComputedStyle(box, null).getPropertyValue('padding-top'));`, with `var box = document.getElementById('box');` That would return '20px', which you can subtract from clientWidth / clientHeight. If you do that for all padding values you should be good to go. – Daniël Knippers Apr 28 '14 at 07:40
  • @daniel-knippers Would you please post that as an answer, particularly the `window.getComputedStyle` part was exactly what I needed to do that math myself. – ThorSummoner Apr 28 '14 at 07:56

3 Answers3

5

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;
Community
  • 1
  • 1
Daniël Knippers
  • 3,049
  • 1
  • 11
  • 17
-2

Try this using jquery: http://codepen.io/anon/pen/shoun

$(document).ready(function(){
  $("pre").append("Total Height = " + ($("#box").height() - parseInt($("#box").css("padding-top"))));
});
Mayank Tripathi
  • 1,346
  • 7
  • 21
-3

Well, you could try:

element.clientHeight    
element.clientWidth

-or-

element.offsetWidth
element.offsetHeight

depending on what you want, but we'd need some code to really help you out.

davidpm4
  • 562
  • 1
  • 7
  • 22