CSS Margins

Space outside an element.

✍️ 3 exercises + code challenge in this lesson

Margins create space outside an element's border.

  • margin-top, margin-right, margin-bottom, margin-left
  • Shorthand with 4 values: margin: top right bottom left;
  • 2 values: margin: 10px 20px; → top/bottom 10px, left/right 20px.
  • margin: 0 auto; horizontally centres a block with a set width.
Margin collapse: when two vertical margins meet, only the larger one is used, not the sum.

Key Takeaways: CSS Margins

Mastering CSS Margins helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Margins Code Example

CSS
<style>
  div { background: #DBEAFE; border: 1px solid #2563EB; }
  .a { margin: 20px; }
  .b { margin: 10px 60px; }
  .c { width: 200px; margin: 20px auto; text-align: center; background: #CCFBF1; }
</style>

<div class="a">margin: 20px</div>
<div class="b">margin: 10px 60px</div>
<div class="c">margin: 20px auto (centred)</div>
Free sign-in required · Google login available

CSS Margins Practice Exercises

Check what you learned in “CSS Margins”.

/ 3 solved
Fill in the blank

Centre a block that has a fixed width.

div {
  width: 300px;
  margin: 0 ;
}
✓ Correct! Not quite. Try again.
Multiple choice

Margins create space…

✓ Correct! Not quite. Try again.
Code challenge

Give the paragraph a top margin of 40px.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services