2059↗learn.

The box model

Understand the space around every element.

Four layers

The content is surrounded by padding, then a border, then margin. Padding is inside the border. Margin separates the box from its neighbors. A background paints the content and padding areas.

Predictable sizing

With box-sizing: border-box, a declared width includes content, padding, and border. With the default content-box, padding and border are added outside that width. Margin is outside in both models.

Inspect the difference

In the example, the card stays 260 pixels wide including its padding and border. Change padding to 40px: the content area shrinks while the outer width stays the same.

Try the example

<style>
  * { box-sizing: border-box; }
  body { font-family: sans-serif; background: #f7f8f2; padding: 24px; }
  .card { width: 260px; max-width: 100%; padding: 24px; border: 2px solid #526d14; margin: 20px 0; background: #d4ef78; }
</style>
<div class="card">
  <h1>Room to breathe.</h1>
  <p>Content. Padding. Border. Margin.</p>
</div>

Enable JavaScript to edit and run the example in the playground.

Your turn

Change the padding to 40px, then change the margin to 40px. Compare the result.

Check your understanding

With border-box, what does width include?

  • Only the content
  • Content, padding, and border
  • Content and margin
Show answer and explanation

Content, padding, and border. border-box includes content, padding, and border in the declared width. Margin remains outside.

MDN reference ↗

Next lesson →

Search by topic, concept, or language. Escape to close.

Reset local data?