When designing a web layout, spacing is everything. One of the simplest and most common spacing tasks in CSS is setting equal margins on all sides of an element. Whether you’re centering a button or creating consistent padding around a card, equal margins help maintain balance and alignment in your design.
In this post, we’ll answer the question:
How do you set equal margins on all sides using CSS?
And we’ll show you the most effective ways to do it.
✅ The Simplest Way: margin Shorthand
The most straightforward way to set equal margins on all four sides—top, right, bottom, and left—is to use the margin shorthand property with a single value.
Syntax:
margin: <value>;
Example:
.box {
  margin: 20px;
}
This applies 20px of margin to all four sides of the .box element.
📐 How It Works
When the margin property is given one value, that value is applied equally to:
margin-topmargin-rightmargin-bottommargin-left
This approach is clean, concise, and widely supported in all browsers.
💡 Use Any Valid CSS Unit
You’re not limited to pixels. You can use:
px(pixels)em(relative to font size)%(relative to containing element)rem(relative to root font size)vw/vh(viewport width/height)
Example:
.container {
  margin: 2rem;
}
🎯 Use Case: Centering Elements
One popular use of equal side margins (especially horizontal) is centering a block-level element:
.centered-box {
  width: 300px;
  margin: 0 auto;
}
This sets the top and bottom margin to 0, and left and right to auto, which centers the element horizontally in its container.
🧪 Bonus: Using inherit or initial
You can also set all margins to inherit from the parent or revert to the browser’s default:
margin: inherit; /* Inherits margin from parent */
margin: initial; /* Resets to default (usually 0) */
📝 Conclusion
To set equal margins on all sides of an element in CSS, simply use the margin shorthand with a single value:
margin: 20px;
It’s a clean and efficient way to apply uniform spacing around your elements. Understanding and leveraging this technique helps keep your CSS concise, readable, and maintainable.