1

I've been developing websites for 3 years now and today found something which I couldn't understand. The code I am working with: http://pastie.org/1439629

<!DOCTYPE html>
<head>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8">
 <title>Page Title</title>
 <style type="text/css" media="screen">
  .box{
   margin:50px 0;
   background:red;
   border:1px solid black;
  }
 </style>
</head>
<body>
 <div class="box">
  Y
 </div>

 <div class="box">
  X
 </div>
</body>

Now the issue is, I cant figure out why the two Divs with the class BOX are sharing the same margin space. i.e. the bottom margin on Y is same as top margin of X. Shouldn't there be 100pixel space between the two instead of 50px?

Edit: If i edit CSS to

.box{
    margin:50px;
    background:red;
    border:1px solid black;
    float:left;
    height:50px;
    width:50px;
}

then the distance between the two should still be 50px, but no! now its 100pixel. Why?

Sorry for such a trivial question but i couldn't figure out.

Tarun
  • 5,374
  • 4
  • 22
  • 32

2 Answers2

5

That behaviour is part of the html standard. see: http://www.w3.org/TR/CSS21/box.html#collapsing-margins

Steven K.
  • 2,097
  • 16
  • 15
1

i think after 50px margin from bottom for div y , div x check margin top and it is 50px. then no need to margin 50 px from top again.

imez
  • 308
  • 1
  • 4
  • 14
  • I know that I can give only bottom-margin:50px for spacing of 50px after each div and use left-child property to make sure last div doesn't have 50px after it. But my question is, why are the margins combining? – Tarun Jan 08 '11 at 09:16
  • check this link . http://stackoverflow.com/questions/3906640/css-margins-overlap-problem – imez Jan 08 '11 at 09:19