Šime Vidas
Šime Vidas

Reputation: 185933

Is there a way in JavaScript to directly get the content width of an element when box-sizing:border-box is set in CSS?

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?

Upvotes: 8

Views: 347

Answers (2)

James South
James South

Reputation: 10635

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 :)

Upvotes: 4

Šime Vidas
Šime Vidas

Reputation: 185933

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)

enter image description here

Upvotes: 5

Related Questions