treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Almanac

box-sizing

Last updated on:

* {
   -moz-box-sizing:    border-box;   /* Firefox 1, probably can drop this */
   -webkit-box-sizing: border-box;   /* Safari 3-4, also probably droppable */
    box-sizing:        border-box;   /* Everything else */
}

The box-sizing property in CSS controls how the "box model" is handled in regards to page layout. For instance, if you set an element to width: 100px; padding: 20px; border: 5px solid black; the resulting box is 140px wide. That is because the default box-sizing model is content-box, which behaves that way. Through the box-sizing property we can change that to padding-box (in which case the box would be 110px wide with 20px of padding on the inside), or border-box (in which case the box would be 100px wide with 10px of border and 20px of padding on the inside).

See this example comparing default content-box to border-box:


This is particularly useful on things like <textarea> which you need to explicitly set to 100% width if you want it to fill a parent container, but is also likely you want padding on. Without box-sizing, you would an elaborate faking strategy involving extra wrapper elements.

This also makes fluid/float/grid layouts a lot easier where you want to use percentages for the grids but with fixed pixel padding.

More Information

Browser Support

Bug in Firefox with using border-box with min-height and max-height.

Chrome Safari Firefox Opera IE Android iOS
any 3+ 1+ 7+ 8+ ? any
View Comments

Comments

  1. m_gol
    Permalink to comment#

    I know this is not the newest article but it’s still “googlable” and it has a crucial error: a prefix is needed for any Firefox version, even current Firefox Nightly 22. If anyone follows the author’s advice without checking and drops prefixes, the site will be broken completely in Firefox.

    • Jesse

      Good catch, m_gol.

      <a href=”https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing?redirectlocale=en-US&redirectslug=CSS%2Fbox-sizing target=”_blank”>MDN article on box-sizing

Leave a Comment

Use markdown or basic HTML and be nice.