0

I've started to learn html and css and encountered some misunderstanding... Here is some code:

body {
  margin: 0px;
}

#red {
  background: red;
  width: 100px;
  height: 100px;
  margin-top: 55px;
  margin-left: 30px;
}

#green {
  background: green;
  width: 200px;
  height: 200px;
  margin-left: 15px;
  margin-top: 55px;
}
<div id="red"></div>
<div id="green"></div>

Here is the red and the green blocks. The red's margin-top is 55px. And it's calculated from the top of the screen (I think the parent is <html> here). But parent for red block is obviously <body>. So the question is, why does it happen? Why margin is not calculated from the body?

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
Leonid
  • 55
  • 2
  • 10

2 Answers2

3

this is a classic case of 'margin-collapsing' in css

https://css-tricks.com/what-you-should-know-about-collapsing-margins/..

you will find various articles about it ..

just try to give your body a border then you will see it doesnt happen..

read this for other ways to avoid this

How to disable margin-collapsing?

<!DOCTYPE>
<html>
<head>
<title>Why, mr. Anderson?</title>
 <style type="text/css">
 
  body {  
    margin: 0px;
       border: 1px solid red;
  }
   
  #red {
   background:red;
   width: 100px;
   height: 100px;
   margin-top: 55px;
   margin-left: 30px;
  }
   
  #green {
   background:green;
   width: 200px;
   height: 200px;
   margin-left: 15px;
   margin-top: 55px;
  }  
 </style>
</head>
<body>

 <div id="red"></div>
 <div id="green"></div>
 

</body>
</html>
Community
  • 1
  • 1
ashish singh
  • 6,526
  • 2
  • 15
  • 35
1

This is called margin collapsing.

When an element with a margin is inside an element with no padding or border, the margin will be applied outside the parent element instead of between the child element and the parent edge.

The basic reason for this behaviour is that margin specifies the minimum distinace between elements, not a distance around an element like padding specifies distance around the element content.

https://www.sitepoint.com/web-foundations/collapsing-margins/

You can remove margin collapsing by the following ways:

  1. floated elements
  2. absolutely positioned elements
  3. inline-block elements
  4. elements with overflow set to anything other than visible (They do not collapse margins with their children.)
  5. cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
  6. the root element
Piyali
  • 506
  • 2
  • 11