In CSS, the box model[1] describes the rectangular boxes that are generated for elements laid out in the page.
Essentially, everything is a rectangle.
Some interesting facts:
border-radius rounds out the corners of this box.box-shadow adds a shadow to this box.outline and box-shadow aren’t part of the box, and therefore have no effect on the layout.The box-sizing property gives you a little control around how boxes are sized within this model. The two possible values for box-sizing are content-box and border-box[2].
content-boxborder-boxFor example:
Both of these boxes have the following CSS, but one has box-sizing content-box and the other border-box.
.box {
height: 5em;
width: 5em;
padding: 1em;
border: .25em solid
}
content-box
border-box
In the border-box case, the width and height of the .box are 5em, exactly what we set. In the content-box case, the width and height are 7.5em = 5 + (2 * 1) + (2 * .25), since we need to include the padding and border on both sides.
One of the benefits of using border-box is you can set a padding and width of mixed units without creating strange sizing edge cases. One fantastic use for this is creating flexible inputs with a fixed padding size.
In the example below, our input has a specific padding in ems and yet we can still specify a width in % (padding: .4em .55em and width: 100%, respectively).
input[type="text"] {
/* Flexibility */
box-sizing: border-box;
width: 100%;
/* Styling */
padding: .4em .55em;
font-size: inherit;
font-family: inherit;
color: inherit;
border: 0;
border-radius: .25em;
outline: none
}
Box
width:
Adjust the box width and observe the input sizes itself perfectly within the box while maintaining a fixed padding.
If you want height and width to behave in the most intuitive way, listen to Paul Irish[3] and put this at the top of your CSS:
html {
box-sizing: border-box
}
*, *::before, *::after {
box-sizing: inherit
}
padding-box, but don’t worry about that.