Tsallaka zuwa abun ciki
Justice Tech School

Margins

margin adds space outside an element. One value sets all four sides, two values set vertical then horizontal, and four values go top, right, bottom, left. margin: 0 auto centres a block with a set width horizontally.

Vertical margins between neighbouring blocks collapse: the gap is the larger of the two, not their sum. Margins of a parent and its first child can also collapse. Padding, borders and flex or grid containers do not collapse.

Example
<style>
  .box { background: #fde68a; padding: 10px; width: 200px; }
  .a { margin-bottom: 40px; }
  .b { margin-top: 20px; }
  .centered { margin: 30px auto 0; background: #bfdbfe; }
</style>
<div class="box a">Margin-bottom 40px</div>
<div class="box b">Margin-top 20px (gap is 40px, not 60px)</div>
<div class="box centered">Centered with auto</div>

Exercise

Centre this fixed-width block horizontally.

.page {
  width: 600px;
  margin: 0 ;
}

Quiz Test

Two stacked blocks have margins of 40px and 20px between them. What is the gap?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.