html
/

CSS Margin

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

CSS Margin

What is Margin?

Margin is the space outside an element's border. It creates distance between elements.

Basic Margin

CSSRead-only
1
div {
  margin: 20px;
}

Individual Sides

CSSRead-only
1
div {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
}

Shorthand Property

CSSRead-only
1
div {
  margin: 10px 20px 30px 40px;
}

Shorthand Variations

ValuesMeaning
1 valueAll sides
2 valuesTop/Bottom, Left/Right
3 valuesTop, Left/Right, Bottom
4 valuesTop, Right, Bottom, Left

Auto Margin (Centering)

CSSRead-only
1
div {
  width: 200px;
  margin: 0 auto;
}

Negative Margin

CSSRead-only
1
div {
  margin-top: -10px;
}

Margin Collapse

Vertical margins between elements may collapse into a single margin (the larger value is applied).

Example

CSSRead-only
1
h1 {
  margin-bottom: 20px;
}

p {
  margin-top: 10px;
}

Best Practices

  • Use margin for spacing between elements
  • Use shorthand for cleaner code
  • Use auto for horizontal centering
  • Avoid excessive negative margins

Common Mistakes

  • Confusing margin with padding
  • Unexpected margin collapsing
  • Using too many manual margins
  • Overusing negative margins

Conclusion

CSS margin controls spacing outside elements. Understanding it is key for layout and spacing design.

Try it yourself

div {
  width: 200px;
  margin: 20px auto;
}

Test Your Knowledge

Q1
of 3

Margin is space where?

A
Inside
B
Outside
C
Border
D
Center
Q2
of 3

Which centers element?

A
margin: auto
B
margin: 0 auto
C
padding: auto
D
center: true
Q3
of 3

Which is shorthand?

A
margin-top
B
margin
C
margin-left
D
margin-right

Frequently Asked Questions

What is margin?

Space outside an element.

What does margin: 0 auto do?

Centers element horizontally.

What is margin collapse?

Vertical margins combine into one.

Previous

css borders

Next

css padding

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.