CSS · Course navigation

CSS Box Model

Understand content, padding, border, and margin.

On this page

The concept

Every element is a box made of content, padding, border, and margin. With box-sizing: border-box the width includes padding and border, so the box stays the size you set. margin: 1rem auto centers a block with a set width horizontally.

Code example

CSS
.box {
  box-sizing: border-box;
  width: 20rem;
  padding: 1rem;
  border: 2px solid #333;
  margin: 1rem auto;
}

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1.box {
2 box-sizing: border-box;
3 width: 20rem;
4 padding: 1rem;
5 border: 2px solid #333;
6 margin: 1rem auto;
7}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Select every element with the box class.—
—
Width includes padding and border.—
—
Space inside the box, around the content.—
—
The auto side margins center the box.—
—

Behind the scenes

How CSS processes this code

The browser matches selectors, computes styles, and paints the result. CSS does not produce console output.