Chapter 1 The Box

Box model

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.

A picture of the box model[1]

Some interesting facts:

Quick note: most CSS properties in this textbook can be clicked to obtain contextual information. Try clicking box-shadow, for example.

Box sizing

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].

The default. When computing the size of a box, padding and border are added.
When computing the size of a box, padding and border are folded in.

For 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



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.

Flexible inputs

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


  width: 75%

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:

*, *:before, *:after {
    -webkit-box-sizing: border-box; /* Needed for mobile WebKit */
    -moz-box-sizing: border-box; /* Needed for Firefox */
    box-sizing: border-box

Further reading


  1. w3: Box model
  2. MDN: box-sizing — There is also padding-box, but don’t worry about that.
  3. Paul Irish: * { Box-sizing: Border-box } FTW