CSS Box Model

Every HTML element is a rectangular box. The CSS box model describes the four layers of this box, from inside to outside.

The four layers
Margin
Border
Padding
Content

LayerMeaning
ContentThe text or image itself. Set by width and height
PaddingSpace around the content, inside the border
BorderThe line around the padding
MarginSpace outside the border, between this and other boxes

How the total size is calculated

.box {
  width: 200px;
  padding: 20px;
  border: 5px solid #333;
  margin: 10px;
}

With the default box-sizing: content-box, the width is only for the content. So:

  • Total width of the box = 200 + 20 + 20 (padding) + 5 + 5 (border) = 250px.
  • Space it takes on the page = 250 + 10 + 10 (margin) = 270px.

box-sizing: border-box

This is a confusing calculation. box-sizing: border-box makes the width include padding and border, so width: 200px means the box is really 200px wide.

* {
  box-sizing: border-box;
}

Most developers put this rule at the top of every stylesheet.

Note: Think of a gift box: the gift is the content, the bubble wrap is the padding, the box wall is the border, and the gap to the next box on the shelf is the margin.

Summary

  • Each element has content, padding, border and margin.
  • With content-box the total width = width + padding + border.
  • Use box-sizing: border-box for easier sizes.
  • Next: CSS Outline.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.