agyanadda@gmail.com

CSS Margin

CSS Box Model 1 min read Updated Dec 1, 2026 Topic 14 of 39

Margin is the space outside an element's border.

Individual sides

margin-top, margin-right, margin-bottom, margin-left

Shorthand

  • margin: 20px; — all sides
  • margin: 10px 20px; — top/bottom, left/right
  • margin: 10px 20px 30px; — top, left/right, bottom
  • margin: 10px 20px 30px 40px; — top, right, bottom, left (clockwise)

Centre a block

width: 300px; margin: 0 auto; centres a block horizontally.

Margin collapse

Vertical margins of two blocks touching each other combine: 20px and 30px give a 30px gap, not 50px.

Example

Example — Centring with margin auto HTML
<style>
  .card {
    width: 260px;
    margin: 20px auto;
    padding: 16px;
    background: #fff7d6;
    border: 1px solid #e0c96b;
    text-align: center;
  }
</style>

<div class="card">I am centred with margin: 20px auto;</div>

Test Yourself With Exercises

Exercise 1 Multiple Choice

margin: 10px 20px; sets left and right margins to:

Exercise 2 Fill in the Blank

margin: 0 ___; centres a block that has a width.

Exercise 3 True / False

Margins can have negative values.

Frequently Asked Questions

Browsers add a default margin to body and headings. Reset it with body { margin: 0; }.