CSS Margins

Margins create space around elements, outside of any defined borders. They push elements away from their neighbors and container edges.

Margin Properties

The margin property sets space outside an element's border on all four sides.

Individual sides: margin-top, margin-right, margin-bottom, margin-left.

Values can be lengths (px, em, rem), percentages (of parent width), or auto.

Margins can be negative to pull elements closer or create overlap.

/* All sides equal */\n.box {\n  margin: 20px;\n}\n\n/* Vertical | Horizontal */\n.card {\n  margin: 10px 20px;\n}\n\n/* Top | Horizontal | Bottom */\n.section {\n  margin: 10px 20px 30px;\n}\n\n/* Top | Right | Bottom | Left */\n.custom {\n  margin: 10px 20px 30px 40px;\n}\n\n/* Individual sides */\n.spaced {\n  margin-top: 20px;\n  margin-bottom: 40px;\n  margin-left: 0;\n  margin-right: 0;\n}

Margin Auto and Centering

margin: auto centers block elements horizontally within their container.

The element must have a defined width for auto margins to work.

margin: 0 auto sets top/bottom to 0 and left/right to auto, centering horizontally.

Auto margins only work on block-level elements, not inline elements.

/* Center horizontally */\n.container {\n  width: 800px;\n  margin: 0 auto;\n}\n\n/* Center with spacing */\n.content {\n  max-width: 1200px;\n  margin: 40px auto;\n  padding: 20px;\n}\n\n/* Won\'t work on inline */\nspan {\n  margin: auto; /* No effect */\n}\n\n/* Convert to block first */\nspan.centered {\n  display: block;\n  width: 200px;\n  margin: 0 auto;\n}

Margin Collapse

Vertical margins between adjacent elements collapse to the larger of the two margins.

Horizontal margins never collapse.

Parent and first/last child margins can collapse through empty space.

Margins don\'t collapse with padding, borders, or when using flexbox/grid.

/* These margins collapse */\n.first {\n  margin-bottom: 20px;\n}\n\n.second {\n  margin-top: 30px;\n}\n/* Actual space: 30px (not 50px) */\n\n/* Prevent collapse with border */\n.parent {\n  border-top: 1px solid transparent;\n}\n\n.parent .child {\n  margin-top: 20px; /* Won\'t collapse now */\n}\n\n/* Prevent with padding */\n.container {\n  padding: 1px 0;\n}