CSS Margin
The margin property controls the space outside an element’s border. It creates spacing between elements and helps with layout, positioning, and responsiveness. Margins are transparent and do not have background color.
Margin Syntax
The margin property can be written using: individual sides or shorthand.
Syntax:
margin: top right bottom left;
margin-top: value;
margin-right: value;
margin-bottom: value;
margin-left: value;
Margin – Individual Sides
Example:
.box {
margin-top: 20px;
margin-right: 30px;
margin-bottom: 20px;
margin-left: 10px;
background-color: lightblue;
padding: 10px;
}
Output:
Margin – Shorthand
The shorthand uses 1, 2, 3, or 4 values.
Syntax:
margin: all;
margin: top bottom;
margin: top right-left bottom;
margin: top right bottom left;
1 Value — Applies to all sides
Example:
.box { margin: 20px; }
2 Values — top-bottom, left-right
Example:
.box { margin: 20px 40px; }
3 Values — top, left-right, bottom
Example:
.box { margin: 10px 30px 50px; }
4 Values — top, right, bottom, left
Example:
.box { margin: 5px 10px 20px 40px; }
Margin: auto
Using margin: auto horizontally centers a block element (when it has a width).
Example:
.center-box {
width: 200px;
margin: auto;
background-color: lightgreen;
padding: 10px;
}
Output:
Margin vs Padding
- Margin = space outside the border
- Padding = space inside the border
Negative Margins
Margin values can be negative, which pulls elements closer.
Example:
.box { margin-top: -20px; }
Output:
Paragraph 1
Paragraph 2 (pulled upward with negative margin)