LESSON 13

Margin

Learning objective: Create space between elements with margin.

Understand

Margin is the space around the outside of an element.

margin adds space outside the border, pushing neighbours away. You can set all sides at once, or individually with margin-top, margin-left, etc. margin: 0 auto is the classic trick to center a fixed-width block horizontally.

Analogy: Margin is the personal space an element keeps from its neighbours.

See It in Action

Centering with auto margins:

.box {
  width: 300px;
  margin: 0 auto;
}
How it works: Top and bottom margins are 0; left and right are auto, which splits the leftover space evenly and centers the box.

Try It Yourself

  1. Add margin between two stacked boxes.
  2. Center a fixed-width box with margin: 0 auto.
  3. Set different margins per side.

Quick Quiz

What does margin: 0 auto commonly do?

Challenge

Space out and center a set of boxes using margins.

Success condition: Your boxes have even spacing and one is horizontally centered.