CSS Tutorial

The Box Model

Margin, Border, Padding, and Content: The geometry of CSS

Everything is a Box

In CSS, every single element on the page is treated as a rectangular box. Understanding how these boxes are measured is the most important skill in CSS layout.
The Box Model consists of four layers:
  1. Content: The text or image itself.
  2. Padding: Clear space inside the border (background color shows here).
  3. Border: A line around the padding and content.
  4. Margin: Clear space outside the border (separates the box from others).

Box Sizing (The "Gotcha")

Wait! By default, if you set width: 100px; and padding: 10px;, the box actually becomes 120px wide. This is very confusing and breaks layouts.
To fix this, we use box-sizing: border-box;. This tells the browser: "The width I set includes the padding and the border."
css
* {
  box-sizing: border-box; /* The Industry Standard */
}

Margin vs. Padding

FeaturePaddingMargin
LocationInside the boxOutside the box
BackgroundShows the backgroundAlways transparent
ClickableYes (if the element is a link)No
CollapsingNoYes (Vertical margins can merge)

Summary

TermDescription
contentThe core data
paddingInternal breathing room
borderThe container edge
marginExternal separation
box-sizingHow width/height are calculated
Best ForControlling spacing and sizing of elements
Logic"Layered geometry"
SafetyAlways use border-box to avoid layout math headaches
ModernThe foundation of every grid and flexbox layout
StandardUse margin: auto to center a block element horizontally
IdentityThe "Skeleton" of the web