CSS margin Property
The margin property in CSS controls the space outside an element, creating separation between elements in a webpage layout.
1. Syntax
value→ Defines the space (e.g.,10px,1em,5%,auto).- Common units: pixels (
px), percentages (%), em, rem, auto.
2. Margin for Each Side
| Property | Description |
|---|---|
margin-top | Sets margin at the top. |
margin-right | Sets margin on the right. |
margin-bottom | Sets margin at the bottom. |
margin-left | Sets margin on the left. |
Example:
✅ Applies different margins to each side.
3. Shorthand Margin (One Line)
| Syntax | Explanation |
|---|---|
margin: 20px; | 20px for all sides. |
margin: 10px 20px; | 10px top & bottom, 20px left & right. |
margin: 10px 15px 20px; | 10px top, 15px left & right, 20px bottom. |
margin: 5px 10px 15px 20px; | 5px top, 10px right, 15px bottom, 20px left (clockwise order). |
Example:
✅ Top → Right → Bottom → Left (Clockwise Order).
4. Auto Margin (Centering an Element)
Using margin: auto; centers a block element horizontally.
✅ The element stays in the center of the page.
5. Negative Margins
Margins can have negative values to pull elements closer.
✅ Moves the element 20px closer to the previous element.
6. Margin Collapse (Overlapping Margins)
If two elements have adjacent vertical margins, only the larger margin applies (not the sum).
✅ Effective margin = 30px, not 20px + 30px = 50px.
7. Margin vs Padding (Difference)
| Property | Effect |
|---|---|
margin | Adds space outside an element (between elements). |
padding | Adds space inside an element (between content and border). |
Example:
8. Removing Margin (margin: 0;)
✅ Removes default margins from all elements.
9. Browser Support
✅ Fully supported in all browsers.

