🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
CSS MASTER CLASS /// VISUAL ENGINEERING /// LAYOUT DESIGN /// ANIMATION LAB /// CSS MASTER CLASS /// VISUAL ENGINEERING ///
Total XP: 0|💻 css XP: 0

Margin & Padding in CSS3: Styling & Design

Learn about Margin & Padding in this comprehensive CSS3 web design tutorial. Master the whitespace. Learn the TRBL clockwise rule, discover the magic of auto margins for centering, and understand the tricky behavior of margin collapsing.

LOADING ENGINE...

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Whitespace Engineering

Whitespace and Rhythm. Command the fundamental physics of the box model to enforce pixel-perfect spacing, alignment, and separation of components.


Margin and Padding are the two pillars of whitespace. While they both create distance, they serve completely different roles in the visual hierarchy of a page.

1The Spacing Shorthand

Writing separate properties for every side is inefficient. CSS provides powerful shorthand:

  • 1 Value: padding: 10px (All sides 10px).
  • 2 Values: padding: 10px 20px (Top/Bottom 10px, Right/Left 20px).
  • 3 Values: padding: 10px 20px 30px (Top 10px, Right/Left 20px, Bottom 30px).
  • 4 Values: padding: 10px 20px 30px 40px (Clockwise: Top, Right, Bottom, Left). Remember the mnemonic TRBL (Trouble) to never forget the order.

2The Physics of Collapsing

Margins have a unique behavior called 'Collapsing'.

  • Vertical Only: Horizontal margins never collapse.
  • Adjacent Siblings: When two vertical margins meet, the larger one wins, and they don't add together. If a top element has margin-bottom: 50px and the next has margin-top: 30px, the distance between them is 50px, not 80px.
  • Padding doesn't collapse: If you need space that always adds up, use padding inside a parent or borders to prevent collapsing.

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Lesson Glossary

[01]padding

Internal space between content and border. Shares the background color.

Code Preview
padding

[02]margin

External transparent space around an element, used to separate it from others.

Code Preview
margin

[03]TRBL

Mnemonic for the clockwise shorthand order: Top, Right, Bottom, Left.

Code Preview
TRBL Rule

[04]auto margin

A value that tells the browser to automatically calculate and split the remaining space.

Code Preview
margin: auto

[05]margin collapse

A CSS behavior where adjacent vertical margins combine into the larger of the two.

Code Preview
Collapsing

[06]shorthand

A way to set multiple side properties in a single line.

Code Preview
margin: 10px 20px;

Continue Learning