CSS Margin and Padding
CSS Margin and Padding
Margin separates neighboring boxes; padding creates comfortable room inside a box.
What you’ll learn
- Distinguish external margins from painted padding.
- Read two- and four-value shorthand.
- Recognize when vertical margins may collapse.
Understand the concept
Padding adds space between content and border. Margin adds space outside the border and can create separation between cards, headings and sections. Shorthand follows a clockwise pattern: top right bottom left, while two values mean vertical then horizontal.
For block elements in normal flow, adjacent vertical margins may collapse instead of adding together. Padding does not collapse. Margin auto can also center a block with a constrained width.
What the browser evaluates
Use padding for an element’s inner surface, margin for external separation. A background color normally paints through padding but not through margin.
Padding is painted
The background extends into the extra internal space.
HTML
<div class="pad">Padding surrounds content.</div>CSS
.pad { background: #bfdbfe; padding: 24px; border: 2px solid #2563eb; }Rendered output
Observe: The space around the words is blue because padding lies inside the border.
Margin is outside
Separate two panels using outer space.
HTML
<div class="stack"><div class="panel">First</div><div class="panel">Second</div></div>CSS
.stack { background: #f1f5f9; padding: 1px; }
.panel { padding: 12px; margin: 14px; border: 1px solid #0f766e; background: #ccfbf1; }Rendered output
Observe: The gray gaps outside each green panel show margin space.
Explain the result
Use padding for an element’s inner surface, margin for external separation. A background color normally paints through padding but not through margin.
Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.
Common mistakes to avoid
- Vertical margins in normal block flow may collapse instead of adding.
- Margin does not extend the element’s background color.
Try it yourself
Change the panel margin to 8px 24px. Predict the top/bottom and left/right gaps.
Before changing the code, predict what will change. Then verify by checking the rendered result.
Check your understanding
What you should remember
Padding is inner breathing room; margin is outer separation.
Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.
Reaching the recap and completing the quizzes are separate milestones.