Margins are used to create space around elements, outside of any defined borders. The margin property clears an area outside the border of an element.
CSS has properties for specifying the margin for each side of an element:
margin-topmargin-rightmargin-bottommargin-leftp {
margin-top: 40px;
margin-bottom: 20px;
margin-left: 50px;
margin-right: 30px;
}
To keep your CSS code clean, you can specify all margin properties in one single property. The order of the values is: Top, Right, Bottom, Left.
/* Four values: Top, Right, Bottom, Left */
margin: 25px 50px 75px 100px;
/* Three values: Top, Right/Left, Bottom */
margin: 25px 50px 75px;
/* Two values: Top/Bottom, Right/Left */
margin: 10px 20px;
/* One value: All four sides */
margin: 20px;
If you set the margin property to auto, it will horizontally center an element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
div {
width: 300px;
margin: auto; /* Centers the box horizontally */
}
Unlike padding, margins can have negative values. This allows you to pull elements closer together or even make them overlap.
p {
margin-top: -10px; /* Pulls the element up */
}
Sometimes the top and bottom margins of elements are collapsed into a single margin that is equal to the largest of the two. This does not happen on left and right margins!
margin: auto to center vertically too. By default it only centers horizontally on a block element with a set width — vertical centering needs Flexbox or Grid instead.
margin-bottom: 20px and margin-top: 20px don't add up to 40px of gap — the larger one wins and they collapse into a single 20px gap.
Combining margin: auto centering with margin-bottom spacing between list items — a compound example closer to real layout work:
.card {
width: 60%;
margin: 0 auto 20px; /* centered, with space below */
}
.card li {
margin-bottom: 8px;
}
Rendered result:
Q: Why did my top margin seem to disappear?
A: It likely collapsed with an adjacent element's margin — that's expected behavior, not a bug. Padding on a parent, or display: flex, prevents collapsing.
Q: Can margin be a percentage?
A: Yes — a percentage margin is calculated relative to the width of the containing block.
Q: Does margin work on inline elements?
A: Horizontal margin (left/right) works on inline elements, but vertical margin (top/bottom) is ignored. See the MDN margin reference for the full behavior by display type.