The margin property in CSS is used to create space outside an element’s border. By adjusting margins, you control the spacing between elements and how they are positioned on the page.
Think of margin as the outer “bubble” around an element — more margin means more free space around it.
top, right, bottom, and left separately.margin shorthand lets you set all four sides in one line.px, em, and %.margin: auto; is commonly used to center block elements horizontally.Basic margin syntax for any selector:
/* Basic margin syntax on all sides */
selector {
margin: value;
}
You can also control each side individually:
/* Individual margin properties */
selector {
margin-top: value;
margin-right: value;
margin-bottom: value;
margin-left: value;
}
Common shorthand patterns:
margin: top right bottom left;margin: top-bottom left-right;margin: top left-right bottom;margin: all-sides;| Property | Description | Example Value |
|---|---|---|
margin |
Sets margin on all four sides | 20px, 2em, 10% |
margin-top |
Sets margin on the top side | 10px |
margin-right |
Sets margin on the right side | 15px |
margin-bottom |
Sets margin on the bottom side | 10px |
margin-left |
Sets margin on the left side | 15px |
Example 1 · Uniform & directional margins
/* Uniform margin on all sides */
.container {
margin: 20px;
}
/* Vertical margin (top and bottom) */
.vertical-margin {
margin: 10px 0;
}
/* Horizontal margin (left and right) */
.horizontal-margin {
margin: 0 20px;
}
Example 2 · Centering with auto
/* Center a block element horizontally */
.center-box {
width: 300px;
margin-left: auto;
margin-right: auto;
}
/* Shorter syntax using shorthand */
.center-box-short {
width: 300px;
margin: 20px auto;
}
Example 3 · HTML structure using margin classes
<!-- Boxes using different margin utilities -->
<div class="container">
<div class="vertical-margin">Vertical margin example</div>
<div class="horizontal-margin">Horizontal margin example</div>
<div class="center-box-short">Centered box with margin auto</div>
</div>
In the example below, the outer box has a margin applied. This creates space between the element and any content around it. The padding inside the box keeps the text away from its border.
This box has a margin applied around it, creating space between the element and surrounding content.
If you reduce the margin, the dashed border will move closer to other elements on the page. Increasing the margin will push it further away.
margin: 10px;, not margin: 10;).margin adds space outside the element, while padding adds space inside it.margin: auto; (with a fixed width) to center block elements horizontally in their container.margin value. Observe how the spacing between them changes.margin-top, margin-bottom, margin-left, and margin-right individually on a single element and note how each side is affected.300px) and center it using margin: 40px auto;.margin-left: 10%;) and see how they react to different screen sizes.