What is the CSS Box Model?

// Quick Answer
  • Every HTML element is a rectangular box.
  • The box model consists of content, padding, border, and margin.
  • It controls spacing and layout in CSS.
  • It affects the total size of elements.

What is the CSS Box Model?

The CSS Box Model describes how every HTML element is treated as a rectangular box.

Each box is made up of four layers: content, padding, border, and margin.

πŸ’‘ Simple idea

Every element on a webpage is a box inside a box.

Parts of the box model

1. Content

The actual text, image, or media inside the element.

2. Padding

Space between the content and the border.

3. Border

The line surrounding the padding and content.

4. Margin

Space outside the border that separates elements from each other.

Visual example

+-----------------------------+
|          Margin             |
|  +-----------------------+  |
|  |       Border         |  |
|  |  +---------------+    |  |
|  |  |   Padding     |    |  |
|  |  |  Content      |    |  |
|  |  +---------------+    |  |
|  +-----------------------+  |
+-----------------------------+

CSS example

div {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  margin: 30px;
}

How size is calculated

The total size of an element includes:

  • Content width + height
  • Padding
  • Border
  • Margin (outside space)
πŸ“Œ Important

By default, width and height apply only to the content box (not padding or border).

Box-sizing property

You can change how size is calculated using box-sizing:

* {
  box-sizing: border-box;
}

This makes layout easier because padding and border are included in the element’s width.

Real-world usage

  • Spacing buttons and cards
  • Creating layouts
  • Designing responsive grids
  • Controlling visual hierarchy

Summary

The CSS Box Model is the foundation of layout in web design. Every element is a box made of content, padding, border, and margin.

Understanding it is essential for controlling spacing and building clean layouts.