โ† HTML & CSS Basics

The Box Model

~300 words ยท 2 min read

Every element is a box

Browsers render each element as a rectangular box made of four layers, from inside out: content, padding, border, and margin. Understanding how these add up is the foundation of layout.

The four layers

  • Content โ€” the text or image itself.
  • Padding โ€” space inside the box, between content and border. Takes the element's background.
  • Border โ€” a line drawn around the padding.
  • Margin โ€” space outside the border, pushing other elements away. Transparent.

The width problem

By default, the width you set applies only to the content. So a width: 200px box with 20px padding and a 5px border actually occupies 250px โ€” the math gets painful fast.

The fix: box-sizing

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

With border-box, the declared width includes padding and border. A 200px box stays 200px total โ€” the content area simply shrinks. This is the universal reset used by virtually every modern stylesheet.

Padding vs margin

Padding sits inside the border and inherits the background colour; margin sits outside and is transparent. Margins between adjacent elements also collapse โ€” two stacked 20px margins merge into 20px, not 40.

Display types

  • block โ€” takes full width, starts on a new line (div, p).
  • inline โ€” takes only content width, no line break, ignores width/height (span, a).
  • flex โ€” turns children into flexible items along an axis.
Margins collapse; padding doesn't. That single difference explains most mysterious gaps โ€” or missing gaps โ€” in your layouts.