CSS Margins

Margin Basics

The margin property controls spacing outside the border of an element.

div {
  margin: 20px;
}

Individual Sides

You can target specific sides of an element:

div {
  margin-top: 10px;
  margin-right: 15px;
  margin-bottom: 30px;
  margin-left: 5px;
}

Margin Shorthand

Use shorthand to combine multiple margin values:

/* Top, Right, Bottom, Left */
div {
  margin: 10px 20px 30px 40px;
}

Auto Centering

To center a block element horizontally, set margin: 0 auto and define a width.

div {
  width: 300px;
  margin: 0 auto;
}

Collapsing Margins

When two vertical margins meet, only the larger margin is used. This is known as margin collapsing.

<p style="margin-bottom: 30px;">Paragraph 1</p>
<p style="margin-top: 50px;">Paragraph 2</p>

Despite the combined values, the space between them will be 50px, not 80px.

Practice Prompt

Create two stacked elements and experiment with their vertical margins. Try changing:

  • margin-top and margin-bottom
  • applying overflow: hidden to one element to prevent collapsing
<p style="margin-bottom: 30px;">First Paragraph</p>
<p style="margin-top: 50px;">Second Paragraph</p>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic