Margin creates space outside an element’s border. It is part of the box model alongside content, padding, and border. Use it to separate elements or to position a width-constrained block within a wider container. Unlike padding, margin does not add space inside an element’s background. section 3.7 section 12.1.1
Center a content column
Give an inner container a maximum width and set its horizontal margins to auto: `.container { max-width: var(--column-width); margin: 0 auto; }`. The left and right margins expand to fill the remaining space in the outer container. Apply the same width and margins to a header’s inner element to align it with the column below. section 3.1.1
Choose the spacing rule to match what needs to stay aligned or separated:
- Use margin for space outside a container with a background image or color, such as the 40 px below a hero image. Use padding when the space must also surround content inside the container. section 12.1.1
- Use `gap` for repeated spaces between flex items when each item should receive the same separation. Individual margins can become awkward when sidebar links are added, removed, or reordered. section 12.1.1 section 3.6.1
- Account for line height when matching space between text. A 30 px margin between a heading and paragraph can produce more than 30 px between their visible characters because each content box extends beyond its text. section 12.1.2
The four-value `margin` shorthand runs clockwise: top, right, bottom, left. With two values, the first applies to top and bottom and the second to left and right; one value applies to every side. Margins may also collapse with other margins outside a container, creating unexpected spacing. section 1.4.2 section 3.7
Margin can also reserve room beside an element removed from normal flow. For a persistent fixed side menu, a margin on the content container can keep the content from running behind the menu. section 6.1.3
Listing 3.3 Styles for the double container
:root {
--brand-color: #0072b0;
--column-width: 1080px;
}
.page-header h1 {
max-width: var(--column-width); #1
margin: 0 auto; #2
}
.container {
max-width: var(--column-width); #1
margin: 0 auto; #2
}
The listing shows the same maximum width and `margin: 0 auto` applied to a page column and header title so their edges line up. section 3.1.1




