CSS Margin & Padding
The Difference
- Padding — space inside the element (between content and border). Background color fills padding.
- Margin — space outside the element (between elements). Always transparent.
Shorthand Values
CSS
/* 1 value — all sides */ .box { margin: 20px; } /* 2 values — top-bottom left-right */ .box { margin: 10px 20px; } /* 3 values — top left-right bottom */ .box { margin: 10px 20px 30px; } /* 4 values — top right bottom left (clockwise) */ .box { margin: 10px 20px 30px 40px; } /* Longhand */ .box { margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; } /* Same rules apply to padding */
Horizontal Centering with margin: auto
CSS
.container { max-width: 1200px; margin: 0 auto; /* top-bottom: 0, left-right: auto = centered */ } /* auto only works on block elements with a defined width */
Negative Margin
CSS
/* Pull element closer / overlap */ .card { margin-top: -30px; } /* overlaps element above */ .full-bleed { margin: 0 -1.5rem; } /* breaks out of parent padding */
Margin Collapse
CSS
h2 { margin-bottom: 40px; } p { margin-top: 20px; } /* Gap = 40px (the larger wins, they don't add up) */ /* Fixes: use flexbox/grid parent, or use padding instead */ .wrapper { display: flex; flex-direction: column; gap: 1rem; } /* gap doesn't collapse */
Removing Default Browser Margins
CSS
/* Browsers add default margin to body, h1-h6, p, ul etc. */ * { margin: 0; padding: 0; box-sizing: border-box; } /* This "reset" is the first thing in almost every stylesheet */