CSS Box Model

The CSS box model explains how elements are sized. Learn about content, padding, border, and margin.

On this page

CSS Box Model

The CSS box model describes how elements are structured and sized on a web page. Every element is treated as a rectangular box made up of content, padding, border, and margin.

Understanding the box model is essential for controlling layout and spacing in CSS.

Box Model Components

Each element consists of the following parts, from inside to outside:

  • Content – the text or content inside the element
  • Padding – space between the content and the border
  • Border – the edge surrounding the padding
  • Margin – space outside the border

Box Model Example

The example below shows how padding, border, and margin affect the size of an element.

.box {
  width: 300px;
  padding: 20px;
  border: 5px solid #1f4bd8;
  margin: 30px;
}

The total width of this element is larger than 300px because padding, border, and margin are added.

Calculated Size

By default, the total width is calculated like this:

Total width =
content width
+ left padding + right padding
+ left border + right border
+ left margin + right margin

Box Model and box-sizing

The box-sizing property changes how the width and height of an element are calculated.

With content-box (default), padding and border are added to the width and height.

.box {
  box-sizing: content-box;
}

With border-box, padding and border are included inside the defined width and height.

.box {
  box-sizing: border-box;
}

Why Use border-box?

Using border-box makes layouts easier to manage because the element size stays consistent.

  • Widths and heights behave predictably
  • Padding does not break layouts
  • Responsive designs are easier to build

Using border-box Globally

A common best practice is to apply box-sizing: border-box to all elements.

* {
  box-sizing: border-box;
}

Code Challenge

Goal: Create a card layout using the CSS box model.

HTML:

<div class="card">
  <h3>Box Model</h3>
  <p>This card demonstrates the CSS box model.</p>
</div>

Task:

  • Set a fixed width for the card
  • Add padding inside the card
  • Add a border around the card
  • Add margin outside the card
  • Use box-sizing to keep the width consistent

Try a Solution:

.card {
  width: 400px;
  padding: 20px;
  border: 2px solid #1f4bd8;
  margin: 40px auto;
  box-sizing: border-box;
  border-radius: 12px;
}

What’s Next?

Next, you will learn how to draw outlines around elements without affecting layout.

CSS Box Model Examples (9)