CSS Margins
A margin is space outside an element's border. The margin properties set that space on each side of the box.
Push the heading down
The top margin adds space above the heading. The space sits outside the heading itself.
h1 {
margin-top: 40px;
}The four-value shorthand
One declaration sets all four sides. The values run clockwise from the top side.
.box {
margin: 10px 20px 30px 40px;
}Centre the box
The box has a set width. Auto on the left and right margins splits the leftover space evenly.
.box {
width: 300px;
margin-left: auto;
margin-right: auto;
}Example
h1 {
margin-top: 30px;
}
.box {
width: 300px;
margin: 20px 10px;
}
p.intro {
margin-bottom: 25px;
}Key points
- margin-top, margin-right, margin-bottom and margin-left set the four sides.
- The four-value shorthand sets the top, right, bottom and left sides in that order.
- A one-value shorthand sets all four sides to the same space.
- Vertical margins between neighbours collapse into one gap.
- A negative margin value pulls the box closer to its neighbours.
- The auto value centres a block horizontally when the block has a set width.
In this example, the heading gains 30 pixels of space above it. The box takes a two-value margin shorthand. The first value sets the top and bottom space, and the second sets the left and right space. The intro paragraph gains space below it.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Where does a margin sit?