Margins in CSS
? Margins in CSS
Margins create space outside the border of an element. They push elements away from each other, controlling layout spacing.
Margin Properties
margin-topmargin-rightmargin-bottommargin-left
Or shorthand:
margin: top right bottom left;Shorthand Margin Syntax
| Syntax | Effect |
|---|---|
margin: 20px; | All four sides get 20px |
margin: 10px 15px; | Top & bottom: 10px, Left & right: 15px |
margin: 5px 10px 15px; | Top: 5px, Left & right: 10px, Bottom: 15px |
margin: 5px 10px 15px 20px; | Top: 5px, Right: 10px, Bottom: 15px, Left: 20px |
Margin Behavior
Margins collapse vertically between adjacent block elements (only the larger margin applies).
Margins do not collapse horizontally.
Setting
margin: auto;horizontally can center a block element (if it has a width).
Examples
.box { margin: 20px; /* 20px margin all around */}.container { margin: 10px 0; /* 10px top and bottom, 0 left and right */}.centered { width: 300px; margin: 0 auto; /* centers the element horizontally */}Tips
Use margins to control spacing outside elements.
Padding controls spacing inside elements (between content and border).
Beware of margin collapsing when working with vertical spacing.
Want help with margin vs padding or common layout examples using margins?