css margin-top property only works if border is de

2019-04-09 00:48发布

问题:

This question already has an answer here:

  • Why does this CSS margin-top style not work? 11 answers

Well,

It has been sometime since this keep popping in and I never had the time to ask why:

so here is my very simple HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Page Title</title>
  <style>
    div{
      width: 200px;
      background: green;
    }    
    p{
      background: yellow;
      margin: 40px;
    }
  </style>
</head>
<body>
  <div>
    <p>Testing</p>
  </div>
</body>
</html>

nothing particular, only a simple page with a div and a paragraph inside that div.

but you can notice that on the css I declared the paragraph to stay away 40px from divs bounds...and this happens

That's right...top and bottom margin being ignored....

but then if I add a 1px red border to the div like:

div{
  width: 200px;
  background: green;
  border: 1px solid red;
}

here's what I get:

so yes, it really sounds weird for me...this is happening in safari, but I am sure it will happen the same on other browsers...my question would be..why this is happening?

Is there any way to fix it?

Thanks in advance

回答1:

I think you're seeing an example of collapsing margins, which you can read more about here



回答2:

If you add:

overflow: auto;

to the CSS for your div it should take care of the issue.



标签: html margin css