Web Development · Module 3 · Lesson 21 min read

The Box Model

Every element is a box

From the inside out:

  1. Content: the text or image.
  2. Padding: space inside the border.
  3. Border: the line around it.
  4. Margin: space outside, separating it from other elements.
CSS
.card {
  width: 300px;
  padding: 16px;
  border: 1px solid #ddd;
  margin: 20px auto;   /* auto left/right centres a block */
}

box-sizing: the most useful reset

By default, width sets only the content, so padding and border make the box bigger than you asked. Fix it everywhere:

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

Now width: 300px means 300 px including padding and border.

Shorthand order

margin: 10px 20px 30px 40px; goes top, right, bottom, left (clockwise). margin: 10px 20px; means vertical then horizontal.

Margin collapsing

Vertical margins between blocks merge: a 20 px bottom margin above a 30 px top margin gives a 30 px gap, not 50. This doesn't happen in flex or grid layouts.

Seeing it

DevTools → Elements → Computed shows the box model diagram for any element.

Example

HTML
<style>
  *, *::before, *::after { box-sizing: border-box; }
  .card {
    width: 260px;
    padding: 16px;
    margin: 20px auto;
    border: 2px solid #6366f1;
    border-radius: 12px;
    background: #eef2ff;
    font-family: sans-serif;
  }
</style>

<div class="card">
  <strong>260px wide</strong><br />
  including padding and border, thanks to border-box.
</div>