CSS ยท Chapter 9 of 44

CSS Margins

Margin is the transparent space outside an element's border, separating it from neighboring elements.

You can set margin on all sides at once, or individually with margin-top, margin-right, margin-bottom, and margin-left. Using auto for left/right margins centers a block element.

Syntax
margin: top right bottom left;

Margin shorthand

margin: 10px; sets all sides equally. margin: 10px 20px; sets top/bottom then left/right. Four values go clockwise: top, right, bottom, left.

Centering with auto

Setting margin-left and margin-right to auto on a block element with a defined width centers it horizontally.

Example 1 (css)
.card {
  width: 300px;
  margin: 0 auto;
}
Output
A 300px wide box centered horizontally on the page

margin: 0 auto sets no top/bottom margin and centers the box using auto left/right margins.

Key points

  • Margin is space outside the border.
  • Shorthand order for 4 values: top, right, bottom, left.
  • margin: 0 auto centers a block element horizontally.
  • Margins can collapse vertically between adjacent elements.
๐Ÿ’ก Note: Vertical margins between siblings can 'collapse' into the larger of the two values.

๐Ÿ“ Quick Quiz

1. Margin is space:

2. What does margin: 0 auto; do to a block element?

3. In shorthand with 4 values, what is the order?