🌱BeginnerCSS Box Model
CSS Margins and Padding
Control spacing inside (padding) and outside (margin) elements, including shorthand notation and margin collapsing.
Overview
Margin and padding are the two spacing properties in CSS. Both accept values in any CSS unit and both support a shorthand notation.
**Padding** is space between the content and the border. It is inside the box the element's background extends into padding.
**Margin** is space outside the border between the element and its neighbors. Margin is always transparent.
**Shorthand values:**
- 1 value: all four sides `margin: 16px`
- 2 values: top/bottom, left/right `margin: 16px 32px`
- 3 values: top, left/right, bottom `margin: 8px 16px 24px`
- 4 values: top, right, bottom, left (clockwise) `margin: 8px 16px 24px 0`
**Margin collapsing:** When two vertical margins meet (e.g., the bottom of one block and the top of the next), they collapse into a single margin equal to the larger of the two. This only happens with vertical margins.
Key Points
- •padding: space inside the border background color fills padding
- •margin: space outside the border always transparent
- •Shorthand: 1 value (all), 2 values (top/bottom, left/right), 4 values (T R B L)
- •margin: 0 auto centers a block element horizontally (needs a defined width)
- •Margin collapsing: adjacent vertical margins merge into the larger one
- •Negative margins are valid and pull elements toward each other
Examples
Shorthand notation
/* All four sides equal */
.box { margin: 16px; }
/* Top/bottom 16px, Left/right 32px */
.box { margin: 16px 32px; }
/* Top 8px, Left/right 16px, Bottom 24px */
.box { margin: 8px 16px 24px; }
/* Top 8px, Right 16px, Bottom 24px, Left 0 (clockwise) */
.box { margin: 8px 16px 24px 0; }The 4-value pattern goes clockwise: T R B L. Remember "TRouBLe".
Centering with margin auto
.container {
width: 960px;
max-width: 100%; /* shrinks on small screens */
margin: 0 auto; /* 0 top/bottom, auto left/right centers it */
}margin: 0 auto only works on block elements with a defined width.
Margin collapsing explained
h1 {
margin-bottom: 32px; /* bottom margin */
}
p {
margin-top: 16px; /* top margin */
}
/* The gap between <h1> and <p> will be 32px (the larger value),
not 32 + 16 = 48px. They collapse. */Margin collapsing only happens vertically (top/bottom), not horizontally.
Common Mistakes
- Expecting margin: auto to center vertically it only works horizontally for block elements
- Forgetting the mnemonic T R B L (TRouBLe) for 4-value shorthand order
- Being surprised by margin collapse debug by adding a border or overflow: hidden to the parent
Note
For consistent spacing, define a spacing scale (4, 8, 12, 16, 24, 32, 48, 64px) and stick to it. CSS variables make this easy: --space-4: 4px; --space-8: 8px; etc.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4