CSS Margins
Learn how to control spacing between elements using CSS margin properties
What are CSS Margins?
CSS margins create space around elements, outside of any defined borders. They control the distance between elements and are transparent - they don't have a background color.
Margin Properties:
- margin - Sets all four margins
- margin-top - Sets the top margin
- margin-right - Sets the right margin
- margin-bottom - Sets the bottom margin
- margin-left - Sets the left margin
Margins in Action
Example Code
/* Margin Properties */ .element { /* Apply margin to all sides */ margin: 20px; /* Vertical | Horizontal */ margin: 20px 10px; /* Top | Right | Bottom | Left (clockwise) */ margin: 10px 20px 30px 40px; /* Individual side margins */ margin-top: 10px; margin-right: 20px; margin-bottom: 30px; margin-left: 40px; /* Auto margin for centering */ margin-left: auto; margin-right: auto; /* Percentage values */ margin: 5%; /* Viewport units */ margin: 5vw; } /* Special margin values */ .special { margin: auto; /* Browser calculates margin */ margin: 0; /* No margin */ margin: inherit; /* Inherit from parent */ }
Margin Syntax Options
Shorthand Notation
The margin property accepts 1-4 values, following the clockwise pattern.
Individual Properties
You can also set each margin side individually for more control.
Margin Collapse
One of the most important concepts to understand about margins is margin collapse. When two vertical margins meet, they collapse into a single margin. The size of the collapsed margin is equal to the larger of the two individual margins.
When Margins Collapse
- Adjacent sibling elements
- Parent and first/last child elements
- Empty blocks (if they have margins)
When Margins Don't Collapse
- Horizontal margins (left/right)
- Elements with padding or borders between them
- Elements with overflow set to anything but visible
- Absolutely positioned or floated elements
- Inline-block elements
Auto Margins and Centering
Horizontal Centering
Using margin: 0 auto;
is a common technique to horizontally center block elements.
Flexbox and Grid Centering
With modern layout techniques, auto margins can be used for more advanced centering.
Negative Margins
Negative margins can be used to pull elements closer together or overlap them. While powerful, they should be used carefully as they can make layouts harder to understand.
Practical Uses
- Overlapping elements for visual effects
- Compensating for unwanted spacing
- Creating custom grid systems
- Micrometer adjustments to positioning