CSS
CSS: How Do You Set Equal Margins on All Sides?
When building web layouts, one of the most common tasks is creating consistent spacing around elements. Whether you’re centering a container or separating elements visually, setting equal margins on all sides can help maintain balance and alignment.
So how do you do that in CSS?
π Use the margin shorthand property with a single value.
β Set Equal Margin on All Sides
To apply the same margin to the top, right, bottom, and left, use:
selector {
margin: 20px;
}
π Example:
.box {
margin: 20px;
}
This means:
margin-top: 20pxmargin-right: 20pxmargin-bottom: 20pxmargin-left: 20px
All four sides receive equal spacing.
β Supported Units
You can use any valid CSS units with the margin shorthand:
- Pixels (
px) - Percentages (
%) - Ems (
em) - Rems (
rem) - Viewport units (
vw,vh) - Keywords like
autoorinherit
Example with %:
.container {
margin: 5%;
}
This gives 5% of the parentβs width/height as margin on all sides.
β Visual Use Case
HTML:
<div class="card">This card has equal margin on all sides.</div>
CSS:
.card {
margin: 30px;
background-color: #f9f9f9;
padding: 20px;
border: 1px solid #ccc;
}
This makes the .card neatly spaced from surrounding content by 30px on every side.
π§Ύ Summary
| Task | CSS Syntax |
|---|---|
| Equal margins on all sides | margin: 20px; |
| Equal spacing with units | margin: 2em;, 5%, etc. |
| Auto spacing (for centering) | margin: 0 auto; |
π§ Conclusion
To set equal margins on all sides of an element, use the margin shorthand with a single value. Itβs a clean, efficient way to control spacing and keep your layout consistent.
Pro Tip: Use margin: auto; when centering elements horizontally inside a parent with a fixed width.
