CodeBlanks Logo Icon CodeBlanks

Margin

CSS course · Beginner · Lesson 29/82

Learn margin, the outer spacing.

What is margin?

margin is the outer space of a box; it pushes neighbor boxes to create distance. Unlike padding, it is transparent, has no background and can be negative. To overlap two boxes, margin: -10px works.

Like padding, each side can be set separately: margin-top, margin-right, margin-bottom, margin-left. The same shorthand shape applies: one, two or four values.

margin collapse

When two block elements stack vertically, their margin-bottom and margin-top do not add up; the larger one wins. This is called margin collapse.

For example, if one paragraph has margin-bottom: 20px and the next has margin-top: 30px, the gap between them is not 50 pixels but 30. Horizontal margins do not collapse; this is vertical only.

Exercise Center the container horizontally

Write a horizontally centered container for the .page selector: use margin: 0 auto. Top-bottom margin is zero, left-right is automatic.

Show example solution
.page {
  margin: 0 auto;
}

Test yourself

  1. What is the key difference between margin and padding?

    • margin pushes neighbor boxes, padding separates content from border
    • padding is transparent, margin takes the background
    • padding can be negative, margin cannot
    • They are exactly the same thing
    Show answer

    margin pushes neighbor boxes, padding separates content from border — Correct. padding fills the content-border gap; margin is the distance to neighbor boxes.

  2. margin collapse math

    /* p { margin-bottom: 16px; }
       next p { margin-top: 24px; } */
    /* the gap between them = ____px */
    Show answer
    /* p { margin-bottom: 16px; }
       next p { margin-top: 24px; } */
    /* the gap between them = 24px */
  3. Match each margin usage

    margin
    Pushes neighbor boxes
    padding
    Separates content from border
    margin: 0 auto
    Centers the box horizontally
    margin: -10px
    Overlaps with neighbor box
  4. What happens when two paragraphs stack vertically?

    • Margin collapse happens only horizontally
    • Margin collapse also applies to padding
    • The vertical gap equals the larger of the two margins
    • The vertical gap equals the sum of the two margins
    Show answer

    The vertical gap equals the larger of the two margins — Correct. Vertical margins do not add; the larger one wins.

All lessons in Beginner