CSS Margins

Margin is the space outside an element’s border. Use it to create gaps between elements. It does not add background color and can even be negative.

1) Margin Shorthand


.card {
  margin: 20px;            /* all sides */
  margin: 10px 20px;        /* top/bottom 10, left/right 20 */
  margin: 5px 10px 15px;     /* top 5, lr 10, bottom 15 */
  margin: 5px 10px 15px 20px; /* top right bottom left */
}

2) Individual Sides


.notice {
  margin-top: 20px;
  margin-right: 0;
  margin-bottom: 20px;
  margin-left: 0;
}
margin:12px
12px 24px
4 8 16 32

3) Center a Block (Horizontal)


.centered {
  width: 300px;
  margin: 0 auto; /* left & right auto */
}

Add a fixed width, then set margin: 0 auto; to center horizontally.

Centered with margin: 0 auto;

4) Collapsing Margins (Vertical)


/* Adjacent vertical margins may collapse to a single margin */
.stack div {
  margin: 20px 0;
}

When two vertical margins touch (like a paragraph followed by another), the larger one wins instead of adding up. Add padding/border on the parent to avoid collapsing.

Item A (margin-bottom: 20px)
Item B (margin-top: 20px)

5) Negative Margins


.pull-up {
  margin-top: -10px; /* may overlap previous element */
}

Use cautiously—negative margins can create overlaps and unexpected layouts.

Previous element
This box has margin-top: -10px; (pulled up)

6) Margin vs Padding


.with-margin {
  margin: 16px;   /* space outside border */
}

.with-padding {
  padding: 16px;  /* space inside border */
}
with-margin (notice outer gap)
with-padding (notice inner space)

7) Inline vs Block Elements


/* Vertical margins on inline elements don't affect layout. */
span { margin-top: 20px; } /* no visible effect */

/* Convert to block/inline-block/flex to use vertical margins */
span.block { display: inline-block; margin: 10px 0; }

Quick Notes:

  • margin controls outer space; padding controls inner space.
  • Use margin: 0 auto to center fixed-width blocks.
  • Vertical margins may collapse; add padding/border to separate.
  • Negative margins are allowed—use with care.
  • Inline elements ignore top/bottom margins unless display is changed.