CSS Box Model

According to CSS, every element on your web page fits into a box. This is known as the CSS Box Model.

Understanding the CSS Box Model will help you lay elements out on your page. It will also help you understand how the elements will react to one another.

The CSS box model

An example box with an unspecified width. The box also has some margin, padding, and borders.

This is our box content. Right now we just have some text. We didn't declare how wide we wanted the box, so it's just going to fill as much space as it's containing block allows.

This page has some margins on the left and right, but other than that our box will stretch to fit the page.

In CSS, the width of the box is only the width of the content./p>

To calculate the actual amount of horizontal space the box will take up, we have to add the margin, border, and padding amounts for each side.

This is the same box as the last one, except now I've specified that it should have a width of 200px. Now the content of the box is 200px wide.

The content of the box above is 200px. However, we have margins, borders and padding on the left and right of the box. The Web Inspector can easily show us this.

alt

By adding all of the margin, borders, and padding on the left and right of the box to the specified width of 200px, we get 264px. The width of the above box is 200px, but the actual amount of horizontal space it takes up is 264px.

200 content + 5 left padding + 10 right padding + 2 left border + 2 right border + 40 left margin + 5 right margin ---------------- 264 pixel width


If we wanted this same box to fit into a space of 400px, we would have to calculate the box width by subtracting the margins, borders and padding.

400 total pixels - 5 left padding -10 right padding - 2 left border - 2 right border -40 left margin - 5 right margin ---------------- 336 pixel width

This box has a width of 336 pixels and will fit in a 400px containing block.

This will become very important once we start getting into advanced CSS layouts.


Additional Reading