margin can take one value, applying it to all four sides, two values, applying the first to top/bottom and the second to left/right, or four values, applying them clockwise starting from the top. Vertical margins between two adjacent block elements collapse together into a single margin equal to the larger of the two, rather than adding together, a behavior specifically called margin collapsing that applies only to vertical margins between certain block-level elements, never to horizontal margins or to margins involving flex or grid items. Setting margin: auto on a block element with a defined width is the classic technique for horizontally centering it within its container.
1Understanding Margin
margin can take one value, applying it to all four sides, two values, applying the first to top/bottom and the second to left/right, or four values, applying them clockwise starting from the top. Vertical margins between two adjacent block elements collapse together into a single margin equal to the larger of the two, rather than adding together, a behavior specifically called margin collapsing that applies only to vertical margins between certain block-level elements, never to horizontal margins or to margins involving flex or grid items. Setting margin: auto on a block element with a defined width is the classic technique for horizontally centering it within its container.
Margin collapsing only affects vertical margins between certain block-level elements in normal document flow — it never applies to horizontal margins, and doesn't apply to flex or grid items, which is a common source of confusion when the exact same-looking margin values behave differently depending on the layout context.
.card {
margin: 20px;
}2Practical Example
Here is a real-world application of Margin showing how it is used in production CSS code.
.container {
width: 400px;
margin: 0 auto;
}3Best Practices
Follow these guidelines when working with Margin:
1. Use margin: auto on a block element with a defined width to horizontally center it within its parent container
2. Account for margin collapsing when stacking block elements vertically, since two adjacent 20px margins collapse into a single 20px gap, not 40px
3. Use a single shorthand margin declaration with one to four values instead of four separate margin-top/right/bottom/left declarations, for more concise, readable CSS
Tip: Margin collapsing only affects vertical margins between certain block-level elements in normal document flow — it never applies to horizontal margins, and doesn't apply to flex or grid items, which is a common source of confusion when the exact same-looking margin values behave differently depending on the layout context.
.card {
margin: 20px;
}