The CSS Box Model Explained
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What the Box Model Is
Every element on a web page is rendered as a rectangular box, and the CSS box model describes what that box is made of. From the inside out, a box has four layers: content, padding, border and margin.
| Layer | What it controls |
|---|---|
| Content | The actual text or child elements, sized by width and height |
| Padding | Space between the content and the border - part of the element's own background |
| Border | A visible (or invisible) line that wraps the padding and content |
| Margin | Space outside the border, separating this box from its neighbors - always transparent |
Visualizing the Layers
.card {
width: 200px;
padding: 16px;
border: 2px solid #cccccc;
margin: 24px;
}Here, the content area is 200px wide, but the box takes up more visual space once padding and border are added - unless box-sizing changes how that width is measured (covered in the Content-box vs Border-box note in this same section).
Margin vs Padding: A Quick Way to Remember
- Padding is "inside the paint" - it shares the element's background color.
- Margin is "outside the paint" - it is always see-through and used to space elements apart.
- Margin between two boxes can collapse into a single gap in some cases (see Margin Collapsing in this section); padding never collapses.
Why the Box Model Matters
Almost every layout bug - text touching the edge of a container, boxes overlapping unexpectedly, elements being wider than their parent - traces back to a misunderstanding of the box model. Learning to picture these four layers makes debugging spacing issues far faster.