Margin, Padding, and Margin Collapsing
Spacing is what gives designs breathing room, elegance, and clarity.
What is it?
Margin controls spacing outside an element's border, while padding controls space inside the border. Margin collapsing is a CSS behavior where vertical margins combine rather than sum.
Why is it used?
Precise spacing establishes visual relationships between components. Knowing how margin collapsing works avoids unexpected vertical gap bugs.
Detailed Explanation
Shorthand syntax:
• 1 value: `padding: 20px` (all 4 sides)
• 2 values: `padding: 10px 20px` (top/bottom, left/right)
• 3 values: `padding: 10px 20px 30px` (top, left/right, bottom)
• 4 values: `padding: 10px 20px 30px 40px` (top, right, bottom, left — clockwise!)
Margin Collapsing:
When two block elements sit on top of each other, their vertical margins do not add up. Instead, the larger of the two margins wins. For example, if Element A has `margin-bottom: 30px` and Element B below it has `margin-top: 20px`, the distance between them is 30px, not 50px.
Syntax Structure
Syntax Blueprint
/* Clockwise: Top Right Bottom Left (TRBL) */
margin: 16px 24px 32px 12px;
padding: 8px 16px;
Code Example
CSS Code
.container {
max-width: 960px;
margin-left: auto; /* Centers block horizontally */
margin-right: auto;
padding: 0 20px; /* Mobile breathing room */
}
.card {
padding: 24px; /* Inner space inside card */
margin-bottom: 24px; /* Space to the next card */
background: #ffffff;
border-radius: 8px;
}
/* Top margin collapses with previous bottom margin */
.card-title {
margin-top: 0;
margin-bottom: 12px;
}
Explanation of the Code
• `margin: 0 auto` is the classic technique to center a fixed-width container horizontally.
• `margin-top: 0` removes unwanted top margin from headings inside card containers.
Expected Output
A horizontally centered container with clean card padding and predictable vertical spacing between items.
Real-World Application
Component libraries standardize spacing scales (e.g. 4px, 8px, 12px, 16px, 24px, 32px, 48px) to keep apps visually harmonious.
Common Mistakes to Avoid
• Trying to use `margin-top` or `margin-bottom` on inline elements like `<span>` (vertical margins are ignored on inline elements).
• Being surprised when adjacent vertical margins collapse together.
Quick Practice Challenge
Center a 600px wide card horizontally on the screen using `margin-left: auto` and `margin-right: auto`.
Key Takeaways
• Remember TRBL: Top, Right, Bottom, Left for 4-value shorthand.
• `margin: 0 auto` centers block elements with a declared width.
• Adjacent vertical margins collapse to the larger margin value.