Where developers come to connect, share, build and be inspired.

110

Avoid box-model disparity with box-sizing: border-box

33401 views

A well-supported --but often misunderstood-- CSS property, box-sizing describes how your content-width, padding and border contribute to the overall width of a block-level element.

The "border-box" value eschews the traditional box-model for something a little more simple-math-friendly. Instead of adding padding and border to a specified width or height, "border-box" places them within. For example, the following element will be 200px wide regardless of the padding value:

/**
 * Normally I would be 222px wide,
 * but with box-sizing: border-box
 * I'll never be wider than 200px!
 */
.slimmer-box {
    box-sizing: border-box;
    border: 1px solid #777;
    padding: 10px;
    width: 200px;
}

You can ascribe the "border-box" model to every element by default with a simple:

* { box-sizing: border-box; }

And the simple inclusion of a box-sizing property standardizes the box-model across all browsers, regardless of rendering mode!

"box-sizing" has been supported in IE since version 8. Other browsers still require a vendor prefix:

-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;

Or you could just use http://modernizr.com/docs/#polyfills

Comments

  • Blank-mugshot
    jmancg

    It might be relevant to mention that in versions prior to Firefox 17, the min-height and max-height properties don't respect box-sizing. It has also been reported that the same occurs on IE9 while running as IE8 browser mode.

  • Blank-mugshot
    dpashkevich

    Chrome, Safari and Opera don't require a prefix for box-sizing anymore... http://caniuse.com/#search=box-siz

Add a comment