2

This is CSS1 code.

div.footer{
background:url('http://i.imgur.com/rfC0Ntb.jpg') repeat-x;
height:88px;
margin:0 auto;
width:400px;
border:1px solid red;
}
div.footer p{
margin-top:40px;
text-align:center; 
border:1px solid red;
}
<body>
    <div class="footer"><p>Copyright&copy; 2013 service center</p></div>
</body>
In css1 40px was added :
1. at the top of box div.footer p.
2.in the box div.footer.
This is css2 code.

div.footer{
background:url('http://i.imgur.com/rfC0Ntb.jpg') repeat-x;
height:88px;
margin:0 auto;
width:400px;
}
div.footer p{
margin-top:40px;
text-align:center; 
}
<body>
    <div class="footer"><p>Copyright&copy; 2013 service center</p></div>
</body>

In css2 ,border:1px solid red was removed from div.footer and div.footer p ,it result in
1.40px was added at the top of box div.footer
2.out of box div.footer
In my opnion there maybe no different effect between css1 code and css2 code,border:1px solid red is to draw a region only,why it can result in the differences?
I want to know the reason,why?

showkey
  • 482
  • 42
  • 140
  • 295
  • http://stackoverflow.com/questions/9519841/why-does-this-css-margin-top-style-not-work – RST May 07 '16 at 08:36

2 Answers2

1

That is margin-collapsing, without border there is nothing to contain the margin of child element. Instead of border you can also fix that with padding or overflow: auto

From MDN

If there is no border, padding, inline content, or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent

div.footer {
  background: url('http://i.imgur.com/rfC0Ntb.jpg') repeat-x;
  height: 88px;
  margin: 0 auto;
  width: 400px;
  padding: 1px;
}
div.footer p {
  margin-top: 40px;
  text-align: center;
}
<div class="footer">
  <p>Copyright&copy; 2013 service center</p>
</div>

div.footer {
  background: url('http://i.imgur.com/rfC0Ntb.jpg') repeat-x;
  height: 88px;
  margin: 0 auto;
  width: 400px;
  overflow: auto;
}
div.footer p {
  margin-top: 40px;
  text-align: center;
}
<div class="footer">
  <p>Copyright&copy; 2013 service center</p>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Try this http://codepen.io/yash02/pen/xVMVEY Play with the css in the code and try commenting the padding and the margin as you asked in the question. Padding was added by me.

Actually the margin you had set which is 40px is taking the margin from top of the page not the div.

Padding will solve the problem

Yash Lotan
  • 378
  • 1
  • 5
  • 21