6

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

no top and bottom margins

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:

working this time

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

Community
  • 1
  • 1
zanona
  • 12,345
  • 25
  • 86
  • 141

2 Answers2

6

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

JamesHalsall
  • 13,224
  • 4
  • 41
  • 66
  • [This is also an old but good article](http://www.complexspiral.com/publications/uncollapsing-margins/) by Eric Meyer on what's going on, and how to stop it. – Matt Gibson Feb 17 '11 at 15:52
2

If you add:

overflow: auto;

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

Shaun
  • 2,446
  • 19
  • 33