CS CSS

CSS: Box Model

What you will learn

Every HTML element is a rectangular box. The box model describes the layers from the content outward: content, padding, border, and margin.

The four layers

div {
    width: 200px;
    height: 100px;
    padding: 20px;       /* space inside the border */
    border: 2px solid black;
    margin: 10px;        /* space outside the border */
}

From inside to outside:

  1. Content — the actual text or child elements. Sized by width and height.
  2. Padding — space between content and border. Transparent by default. Background color extends into padding.
  3. Border — visible edge. Can be styled with border-width, border-style, border-color.
  4. Margin — space outside the border, separating this element from others. Transparent. Collapses vertically.

box-sizing: border-box

By default (content-box), the width and height you set only apply to the content. Padding and border are added on top, making the element bigger than you expected.

/* Default: content-box */
div { width: 200px; padding: 20px; border: 2px solid black; }
/* Actual width = 200 + 20*2 + 2*2 = 244px */

/* border-box: width INCLUDES padding and border */
div { box-sizing: border-box; width: 200px; padding: 20px; }
/* Actual width = 200px (content shrinks to fit) */

Most developers apply border-box globally with *, *::before, *::after { box-sizing: border-box; }.

Margin collapsing

Vertical margins collapse: if a <p> has margin-bottom: 20px and the next <p> has margin-top: 30px, the gap between them is 30px (the larger one wins), not 50px.

Common mistakes

  • Forgetting box-sizing: border-box — causing elements to be wider than expected.
  • Confusing padding and margin — padding adds space inside the border (affects background area), margin adds space outside.
  • Setting width and padding without considering the box model math.
  • Using negative margins for layout — can cause unexpected overlaps.

Quick check below!