← 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
Ready to go further?

These free tutorials are a preview, our Frontend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Frontend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account