The Box Model
The Box Model
Every element in CSS is a rectangular box. The box model defines how content, padding, border, and margin interact to determine an element's total size and spacing.
Four Layers
Each box has four layers, from inside to outside:
.box {
width: 200px;
height: 150px;
padding: 20px; /* Space inside the border */
border: 2px solid #333; /* The border */
margin: 30px; /* Space outside the border */
}
/* Total width: 200 + 20 + 20 + 2 + 2 + 30 + 30 = 304px */
Content is the actual text or image. Padding is space between content and border. Border surrounds the padding. Margin is space outside the border, pushing other elements away.
box-sizing: border-box
By default, CSS uses content-box sizing - the width applies only to content, and padding and border are added on top. This makes layout calculations painful. Switch to border-box where width includes padding and border:
* {
box-sizing: border-box;
}
.box {
width: 200px; /* Now includes padding and border */
padding: 20px;
border: 2px solid #333;
/* Total width is still 200px */
}
Nearly every modern project sets this globally with the universal selector.
Margin Collapsing
Vertical margins between adjacent block elements collapse - only the larger margin applies. Horizontal margins never collapse.
.heading { margin-bottom: 20px; }
.paragraph { margin-top: 30px; }
/* Actual gap between them: 30px, not 50px */
Display Types
The display property changes how an element generates boxes:
display: block; /* Full width, new line */
display: inline; /* Fits content, no new line */
display: inline-block; /* Inline but accepts width/height */
display: none; /* Removes from layout */
Key Points
- Every element is a box with content, padding, border, and margin.
- Use
box-sizing: border-boxglobally to simplify width calculations. - Vertical margins collapse; horizontal margins do not.
display: blockcreates new lines;inlineflows within text.- Understanding the box model is essential for layout and spacing.