Chapter 5

The CSS Box Model

Understand how content, padding, border, and margin combine to control the size and spacing of every element.

In CSS, every element on the page is treated as a rectangular box. Understanding this box model is the key to controlling spacing and size. Each box has four layers, from the inside out: content, padding, border and margin.

The four layers

  • Content: the actual text or image inside the box.
  • Padding: clear space between the content and the border. It pushes the border away from the content.
  • Border: a line drawn around the padding. You can set its width, style and colour.
  • Margin: clear space outside the border that pushes other elements away.
.card {
  padding: 20px;
  border: 2px solid gray;
  margin: 10px;
}

Width and height

By default, the width and height properties set the size of the content area only. This means padding and border are added on top, so the box on screen can look bigger than the number you set.

box-sizing makes life easier

Setting box-sizing to border-box changes this. Now width and height include the padding and border, so the box stays exactly the size you asked for. Many developers apply this to every element.

* {
  box-sizing: border-box;
}

Padding versus margin

A simple way to remember: padding is space inside the box, between content and border. Margin is space outside the box, between this box and its neighbours.

Remember

  • Every element is a box with content, padding, border and margin.
  • Padding is inside the border; margin is outside it.
  • By default width sets only the content size.
  • box-sizing border-box makes width include padding and border.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor