← CSS tutorial

CSS

The Box Model

Every HTML element is a rectangular box made of four layers, from the inside out: content (the text/image itself), padding (space inside the border), border (a visible line around the padding), and margin (space outside the border, between this box and its neighbours).

Example 1: seeing all four layers at once

.box {
  width: 200px;
  padding: 20px;
  border: 4px solid #2f7dff;
  margin: 30px;
}

This box's actual rendered width, by default, is more than 200px — the browser adds the padding and border on top of the content width you set. That surprises almost every beginner at least once.

Example 2: box-sizing fixes the confusing part

.box {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 4px solid #2f7dff;
  /* now the box is EXACTLY 200px wide, padding and border included */
}

box-sizing: border-box changes the rule so width means the total width, padding and border included, rather than just the content. This one line eliminates a huge share of "why is this wider than I set it to be" confusion, which is why many real projects set it globally with * { box-sizing: border-box; } right at the top of their stylesheet.

Try it yourself