← Learning Hub
Beginner

The Box Model

Every element is a rectangular box with four layers, from the inside out:

  • Content - the text or image itself.
  • Padding - space between the content and the border, inside the box.
  • Border - a line around the padding.
  • Margin - space outside the border, pushing other elements away.

Understanding the box model is the key to layout. Think of a framed photo: the photo is the content, the white mount around it is padding, the frame is the border, and the space between this frame and the next one on the wall is the margin.

Padding is inside the box, so it takes the box's background colour - use it to give text breathing room inside a button or card. Margin is outside, always transparent - use it to push boxes apart from each other. When something has "weird extra space", right-click it and choose Inspect in Chrome: the browser shows the box model with each layer coloured.

Example
<!DOCTYPE html>
<html>
  <head>
    <style>
      * { box-sizing: border-box; }
      .card {
        width: 260px;
        padding: 16px;
        border: 3px solid #7c3aed;
        margin: 24px;
        border-radius: 12px;
        background: #f5f3ff;
      }
    </style>
  </head>
  <body>
    <div class="card">Padding is inside the purple border. Margin is the space outside it.</div>
    <div class="card">A second card, pushed down by the margins.</div>
  </body>
</html>
▶ Try it yourself
box-sizing: border-box makes width include padding and border, which makes sizes far easier to predict. Many developers set it on every element, as above.
Key points
  • Every element is a box: content, padding, border, margin.
  • Padding is inside (takes the background); margin is outside.
  • box-sizing: border-box makes widths easy to predict.
  • Use the browser's Inspect tool to see each box.

📝 Test yourself

1. Which space sits inside the border?
2. What does box-sizing: border-box change?
3. Fill in the property for space outside the border:
: 20px;