011. The Spacing Shorthand
EXECUTIVE_SUMMARY // AEO_OPTIMIZED
[Answer Engine Overview: What, Why & How]
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.
022. The 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.
?Frequently Asked Questions
When should I use Margin vs Padding?
Use padding when you want space INSIDE the border, or if you want the background color to extend. Use margin when you want to push OTHER elements away, or if you want transparent space outside the border.
Why is my `margin-top` not working?
You might be experiencing Margin Collapsing. If a parent element has no padding or border, the top margin of its first child will 'collapse' through the parent and push the parent down, rather than pushing the child down inside the parent.
How does `margin: 0 auto` work?
If an element is a block (like a `div`) and has a defined `width`, setting the left and right margins to `auto` tells the browser to calculate the remaining horizontal space and divide it exactly in half, perfectly centering the element.
