CSS Tutorial
CSS Margins
Margins create empty space OUTSIDE an element's border, pushing it away from its neighbors. They are your main tool for spacing elements apart.
What is a margin?
A margin is transparent space on the outside of an element, beyond its border. Margins do not have a color; they simply push other elements away. If two boxes sit too close together, adding margin between them fixes it.
Setting margins on each side
You can set each side separately with margin-top, margin-right, margin-bottom and margin-left. Values are usually in pixels, but percentages and other units work too.
div {
margin-top: 20px;
margin-bottom: 20px;
margin-left: 10px;
margin-right: 10px;
}The margin shorthand
The margin shorthand sets several sides at once. With four values the order is top, right, bottom, left (clockwise). Two values mean top/bottom then left/right. One value applies to all four sides.
margin: 20px; /* all four sides */
margin: 10px 20px; /* top/bottom | left/right */
margin: 5px 10px 15px 20px; /* top | right | bottom | left */See margins in action
<!DOCTYPE html>
<html>
<head>
<style>
.box {
background-color: #2b5cff;
color: white;
padding: 12px;
font-family: Arial, sans-serif;
border: 2px solid #1a3fb0;
}
.spaced {
margin: 30px;
}
</style>
</head>
<body>
<div class="box">No extra margin</div>
<div class="box spaced">This box has 30px margin all around</div>
<div class="box">No extra margin</div>
</body>
</html>Centering with margin: auto
A classic trick is to horizontally center a block element that has a set width by using margin: 0 auto. The browser splits the leftover space equally on the left and right.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
width: 200px;
margin: 0 auto;
background-color: tomato;
color: white;
padding: 16px;
text-align: center;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div class="center">Centered with margin: 0 auto</div>
</body>
</html>Vertical margins between two block elements can "collapse": instead of adding up, the larger of the two margins is used. This is normal CSS behavior called margin collapse.
Margin value patterns
| Syntax | Meaning |
|---|---|
| margin: 20px | All four sides 20px |
| margin: 10px 20px | Top/bottom 10px, left/right 20px |
| margin: 5px 10px 15px 20px | Top, right, bottom, left |
| margin: 0 auto | No top/bottom, auto left/right (centers) |
Margin controls the space OUTSIDE the border, while padding controls space INSIDE it. If in doubt about which to use, ask: do I want to push others away (margin) or breathe room inside (padding)?
Key points
- Margin is transparent space outside the border.
- Set sides with margin-top, margin-right, margin-bottom, margin-left.
- Shorthand order is clockwise: top, right, bottom, left.
- margin: 0 auto centers a fixed-width block horizontally.
- Vertical margins can collapse into one.
