On this page

Box model

12 min read TextCh. 2 — Box Model and Positioning

What is the box model?

Every HTML element is a rectangular "box" composed of four areas, from inside to outside:

  1. Content -- The actual content (text, images)
  2. Padding -- Space between the content and the border
  3. Border -- The visible border of the element
  4. Margin -- Outer space that separates it from other elements

Content area

The content area is where text, images, or other child elements are displayed. Its size is controlled with width and height.

Padding, border, and margin

  • Padding: Inner space. Takes the element's background color
  • Border: Visible border. Defined with border: width style color
  • Margin: Outer space. Always transparent

Box-sizing

By default (content-box), width only applies to the content area. With border-box, the width includes padding and border:

/* Recommended: apply to all elements */
*, *::before, *::after {
  box-sizing: border-box;
}

This makes calculations much more intuitive and is the standard practice in modern web development.

Margin collapsing

Vertical margins between sibling elements collapse: instead of adding up, the larger margin is used. This is an intentional CSS behavior that you need to keep in mind.


In the next lesson, we will learn Flexbox to create flexible layouts.

Practice

  1. Compare content-box and border-box: Create two boxes of 300px width with padding and border. Apply box-sizing: content-box to one and border-box to the other, then measure the final width with the inspector.
  2. Build a card with the box model: Create a card with inner padding, a visible border, and outer margin. Adjust each property until you achieve visually balanced spacing.
  3. Observe margin collapsing: Place two consecutive <div> elements with different vertical margins and verify that the space between them is the larger margin (not the sum).
Caution
Vertical margins collapse. If an element has margin-bottom 20px and the next one has margin-top 30px, the space between them will be 30px (not 50px).
css
/* Recommended global reset */
*, *::before, *::after {
  box-sizing: border-box;
}

.card {
  width: 300px;       /* Includes padding and border */
  padding: 1.5rem;
  border: 1px solid #ddd;
  margin: 1rem;
  border-radius: 8px;
  background: white;
}

/* Margin collapsing */
.section {
  margin-bottom: 2rem; /* Collapses with the next element's margin-top */
}