Set a width. The box must be narrower than its parent.
Use auto on the sides. Left and right share leftover space equally.
Shorthand form.margin: 0.75rem auto keeps vertical margin and centers horizontally.
Modern alternative. Flex/grid centering on the parent is also common.
Edge Cases & Pitfalls
If spacing looks smaller than expected, collapsing or auto rules are often why.
collapse
Vertical margins can collapse
Adjacent top/bottom margins of blocks in normal flow may merge into one margin (the larger value), not a sum.
inline
Top/bottom margin on non-replaced inline
For elements like span, vertical margins do not affect layout. Horizontal margins still apply.
percent
Percentages use the containing block width
Even top and bottom percentage margins resolve against the containing block’s inline size (usually width), not its height.
auto
auto needs leftover space
Horizontal centering with auto fails if the box is full width or not a block-level box with a definite width.
negative
Negative margins pull elements closer
Useful for overlaps, but easy to break responsive layouts. Prefer gap/padding when you only need breathing room.
Compatibility
Browser Support
margin is a browser CSS property for the box model. Node.js, Deno, and Bun do not apply it.
✓ Baseline · Widely available
margin
Supported in all modern browsers and Internet Explorer for many years. Part of the CSS Box Model.
99%Box model support
Google Chrome1+
Full support
Mozilla Firefox1+
Full support
Apple Safari1+
Full support
Microsoft Edge12+
Full support
Opera3.5+
Full support
Samsung Internet1+
Full support
Internet Explorer3+
Full support
marginWidely supported
Bottom line: Safe for every layout. Logical longhands like margin-block are newer; the classic margin shorthand is universal. It is not a runtime API.
Remember
Key Takeaways
Role: outer spacing outside the border on all four sides.
Shorthand: 1–4 values map to sides (clockwise when four).
Center: width + margin: 0 auto for horizontal centering.
Collapse: stacked vertical margins may merge, not add.
One line:margin sets space outside the border — use 1–4 values, or auto to center a sized block.
Frequently Asked Questions
It is a shorthand that sets the outer spacing on all four sides of an element — outside the border — by setting margin-top, margin-right, margin-bottom, and margin-left.
Each side defaults to 0. Browsers may still add margins on elements like p or h1 through their own stylesheets.
Margin is space outside the border, between elements. Padding is space inside the border, between the border and the content.
Give the element a width less than its container, then use margin-left and margin-right as auto — often written as margin: 0 auto.
Yes. Adjacent top and bottom margins of block elements in normal flow can collapse into one margin equal to the larger value.
It is Baseline and widely available in all browsers. It is a browser CSS property for layout, not a Node.js feature.