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: 50pxand the next hasmargin-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.
