CSS Margin

Margins are the outer spacing of an element. The space between the element’s border and surrounding elements. They are essential for layout, alignment, and spacing in CSS.

Key Difference

  • Margin → adds space outside the border (between elements).
  • Padding → adds space inside the border (between content and border).

Specific Margin Properties

You can control each side individually:

Code Block Loading...

Margin Shorthand

The margin shorthand lets you set multiple sides at once. The order is Top → Right → Bottom → Left.

  • 1 value: all sides equal

Code Block Loading...

  • 2 values: top & bottom, left & right

Code Block Loading...

  • 3 values: top, left & right, bottom

Code Block Loading...

  • 4 values: top, right, bottom, left

Code Block Loading...

Accepted Units

Margins accept:

  • px → absolute pixels
  • em/rem → relative to font size
  • % → relative to parent width/height
  • auto → browser calculates margin automatically (commonly used for centering)

Using auto to Center Elements

A classic way to center block elements horizontally:

Code Block Loading...

Modern layouts often use Flexbox:

Code Block Loading...

Negative Margins

Margins can be negative, unlike padding. This allows elements to overlap or shift beyond their normal position.

Examples:

Code Block Loading...

Interactive Playground

Key Takeaways

  • Margins add outer spacing between elements.
  • Use specific properties (margin-top, etc.) for precision.
  • Use shorthand (margin: ...) for convenience.
  • auto is useful for centering elements.
  • Negative margins allow overlapping and shifting elements.