Connect with us

CSS

CSS: How Do You Set Equal Margins on All Sides?

Spread the love

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: 20px
  • margin-right: 20px
  • margin-bottom: 20px
  • margin-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 auto or inherit

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

TaskCSS Syntax
Equal margins on all sidesmargin: 20px;
Equal spacing with unitsmargin: 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.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *