The CSS margin property adds space outside an element’s border. Use it to separate cards, headings, links, and other parts of a layout. Padding serves a different job: it adds space inside an element. On a picture card, for example, margin leaves a gap between the picture’s edge and the card’s dark content panel, while padding keeps text away from the panel’s edge. section 5.4.2 section 8.3.4
Choose the margin that matches the spacing problem:
- Set individual sides when only one gap needs changing: `margin-top: 36px` separates an article from its date, while `margin-bottom: .5rem` adds room beneath a form label. section 4.4.4 section 10.5
- Use shorthand for several sides: `margin: 1rem 0` gives a checkout card top and bottom margins but no left or right margin. `margin: 36px 0 0` adds room above a name while removing its bottom gap. section 8.3.4 section 6.7.1
- Pair a maximum width with `margin: 0 auto` to center content horizontally on wide screens without letting it grow indefinitely. section 4.5.3 section 8.5
When the expected gap disappears
Suppose a checkout card’s heading sits too close to the card edge. Its browser-provided top margin can push the card down instead of making room inside it. Set the heading’s `margin: 0`, give the heading `padding: 1rem`, then give each card `margin: 1rem 0` to restore space between cards. Adjacent margins can collapse into one gap equal to the greater margin, rather than adding together. section 8.3.4
Pulling an image above a profile card
A positive top margin moves an image down; a negative one pulls it up. To show one-third of a profile image above its card, use `margin-top: calc(-1 * var(--imageSize) / 3)`. Give the card enough vertical margin to keep that protruding image visible on short screens: `margin: calc(var(--imageSize) / 3 + 24px) 24px`. section 6.5.2
Browser defaults are worth checking before adding space. Headings and fieldsets can arrive with margins already applied; reset or replace those margins when they work against the design. For spacing that should scale with text size, a `rem` value can help a form avoid looking cramped when text grows. section 6.7.1 section 10.2 section 10.3.1
Listing 8.24 Section margin and header padding
body {
font-family: 'Raleway', sans-serif;
color: #171717;
font-variant-numeric: lining-nums;
background: #fbffff;
padding: 1rem;
}
section { margin: 1rem 0 }
section h2 {
padding: 1rem;
margin: 0;
}
Compare the card’s outer section margin with the heading’s inner padding and zeroed margin. section 8.3.4




