Phase 2CSS Fundamentals

#6 The box model

margin, padding, border, box-sizing

The CSS box model

Every HTML element is a rectangular box. The box model describes how the browser calculates the total size of an element:

Box model layers
/*
  ┌──────────────────────────────────────┐
  │              margin                   │
  │  ┌──────────────────────────────────┐ │
  │  │           border                 │ │
  │  │  ┌──────────────────────────┐    │ │
  │  │  │        padding           │    │ │
  │  │  │  ┌──────────────────┐    │    │ │
  │  │  │  │    content       │    │    │ │
  │  │  │  └──────────────────┘    │    │ │
  │  │  └──────────────────────────┘    │ │
  │  └──────────────────────────────────┘ │
  └──────────────────────────────────────┘
*/

Content, padding, border, margin

Box model properties
.card {
  /* Content size */
  width: 300px;
  height: 200px;

  /* Padding: space inside the border */
  padding: 16px;

  /* Border: the edge of the box */
  border: 2px solid #e0dbd4;

  /* Margin: space outside the border */
  margin: 20px;
}

box-sizing: border-box

By default, width only sets the content width. Padding and border are added on top, making the total box bigger. Use box-sizing: border-box to include padding and border in the width:

border-box
/* Apply to all elements (recommended) */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Now width includes padding + border */
.card {
  width: 300px;    /* Total width = 300px */
  padding: 16px;   /* Included in the 300px */
  border: 2px solid #ddd; /* Included in the 300px */
}

Margin collapsing

Vertical margins between adjacent elements collapse — only the larger margin is applied, not the sum:

Margin collapse
/* These two paragraphs will have 30px between them, not 50px */
.first  { margin-bottom: 20px; }
.second { margin-top: 30px; }

Your turn

Try the box model commands below:

terminal — browser
user@stemlegacy:~$