CSS Tutorial · CSS Basics · Lesson 6 of 19

CSS Box Model

Content, padding, border and margin — and box-sizing: border-box.

Every element is a box

From the inside out:

  1. Content — text or images, sized by width and height.
  2. Padding — space inside the border.
  3. Border.
  4. Margin — space outside, between this box and others.
Example 1Try it yourself
<style>
  .box {
    width: 200px;
    padding: 20px;
    border: 6px solid #2563eb;
    margin: 24px;
    background: #dbeafe;
    font-family: system-ui, sans-serif;
  }
</style>
<div class="box">Content area with padding, border and margin.</div>

Shorthand values go clockwise from the top: margin: 10px 20px 10px 20px (top, right, bottom, left), or margin: 10px 20px (vertical, horizontal). margin: 0 auto centres a block with a width.

box-sizing

By default, width sets only the content width — padding and border are added on top, which makes sizing confusing. Almost every site sets:

*, *::before, *::after { box-sizing: border-box; }

Now width includes padding and border:

Example 2Try it yourself
<style>
  div { width: 200px; padding: 20px; border: 5px solid #7c3aed; margin-bottom: 10px; font: 13px system-ui; }
  .content-box { box-sizing: content-box; }
  .border-box { box-sizing: border-box; }
</style>
<div class="content-box">content-box: 250px wide in total</div>
<div class="border-box">border-box: exactly 200px wide</div>

Use your browser's DevTools (Inspect → Computed) to see the box model of any element.

Test yourself

Which property makes width include padding and border?

  1. box-sizing: content-box
  2. box-sizing: border-box
  3. width: total
  4. display: block
Show answer

Answer: box-sizing: border-box