CSS Margin
CSS margin is used to create space outside an HTML element's border.
Margin is useful when you want to create space between two elements. Unlike padding, margin is located outside the border.
Basic Syntax
selector {
margin: value;
}
Margin Diagram
Simple Explanation
Imagine two HTML boxes placed next to each other.
If the boxes are touching each other, the layout can look crowded.
Margin creates empty space outside the border , helping separate one element from another.
A simple way to remember it is: Padding = inside space and Margin = outside space.
Example 1: Basic Margin
The following example adds 30px of margin on all four sides of the element.
.box {
background-color: lightblue;
border: 2px solid blue;
margin: 30px;
padding: 20px;
}
Output
Example 2: Margin on Individual Sides
You can control the margin of each side separately using four individual properties.
.box {
background-color: lightgreen;
border: 2px solid green;
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
padding: 15px;
}
Output
Different margin values are applied to each side.
Example 3: Margin Shorthand
Just like padding, margin also supports shorthand notation.
.box {
background-color: lightyellow;
border: 2px solid orange;
margin: 10px 20px 30px 40px;
padding: 15px;
}
Output
Margin shorthand controls all four sides.
Margin Shorthand Rule
When four values are provided, CSS applies them clockwise:
10px
20px
30px
40px
margin: 10px 20px 30px 40px;
/*
Top = 10px
Right = 20px
Bottom = 30px
Left = 40px
*/
Example 4: Centering an Element with Auto
One of the most common uses of margin: auto is to center a block element horizontally.
.box {
width: 300px;
background-color: #e9d5ff;
border: 2px solid purple;
margin: 20px auto;
padding: 20px;
}
Output
This box is centered horizontally.
Here, 20px is applied to the top and bottom margins.
The keyword auto allows the browser to distribute the available horizontal space equally on the left and right sides.
Margin Properties
margin-top
Controls the space outside the top border of an element.
margin-right
Controls the space outside the right border of an element.
margin-bottom
Controls the space outside the bottom border of an element.
margin-left
Controls the space outside the left border of an element.
Padding vs Margin
| Padding | Margin |
|---|---|
| Space inside the border. | Space outside the border. |
| Creates space around content. | Creates space between elements. |
| Part of the element's box. | Outside the element's border. |
Summary
CSS margin creates space outside an element's border. You can set margin on all four sides, control each side individually, or use shorthand notation. The value auto is also commonly used to center fixed-width block elements horizontally.