If we set this in CSS (autoprefixed):
* {
box-sizing: border-box
}
then getComputedStyle(elem).width
includes the element's padding.
Live demo: http://jsfiddle.net/simevidas/EpUnp/
I would like to get the width of the element's content box (without the padding). Is there a standard API for this or do I have to manually subtract the padding?
If you set an element's width to 100 pixels, then the element's content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px.
With the CSS box-sizing Property The box-sizing property allows us to include the padding and border in an element's total width and height. If you set box-sizing: border-box; on an element, padding and border are included in the width and height: Both divs are the same size now! Hooray!
To calculate the total width, you must add the padding, border and margin together. This is the default method.
The CSS box-sizing property is used to adjust or control the size of any element that accepts a width or height . It specifies how to calculate the total width and height of that element.
The getBoxQuads API can do it. (It's supported in Firefox Nightly).
var quad = elem.getBoxQuads({ box: 'content' })[0];
var contentWidth = quad.p2.x - quad.p1.x;
Live demo: http://jsfiddle.net/EpUnp/2/ (works in Firefox Nightly)
I don't think there is a standard API for this. I could be wrong though.
My approach would be something like as follows.
Demo
HTML
<div id="box"></div>
CSS
* {
box-sizing: border-box
}
#box {
width:300px;
height:300px;
padding:14px 10px;
background-color:#000;
}
JavaScript
var supports = function () {
var div = document.createElement("div"),
vendors = "Moz Webkit O Ms".split(" "),
len = vendors.length;
return function (prop) {
if (prop in div.style) return true;
prop = prop.replace(/^[a-z]/, function (val) {
return val.toUpperCase();
});
while (len--) {
if (vendors[len] + prop in div.style) {
return true;
}
}
return false;
};
};
var isBox = supports("box-sizing");
var getWidth = function (elem) {
var width = parseFloat(window.getComputedStyle(box).width);
var padding = window.getComputedStyle(box).padding.split(" ");
if (!isBox) {
return width;
}
switch (padding.length) {
case 4:
return width - (parseFloat(padding[1]) + parseFloat(padding[3]));
break;
case 2:
return width - (parseFloat(padding[1]) * 2);
break;
default:
return width - (parseFloat(padding[0]) * 2);
break;
}
}
var box = document.getElementById("box");
alert(getWidth(box));
Rough and ready but seems to work :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With