The css margin-top property only works if a border is declared

Well,

This once went on, and I did not have 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 special, just a simple page with a div and a paragraph inside that div.

but you can notice that on css I announced that the paragraph should remain at a distance of 40 pixels from the borders of the div ... and this happens

no top and bottom margins

That's right ... the top and bottom fields are ignored ....

but if I add a 1px red border to divlike:

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

here is what i get:

working this time

so yes it really sounds weird to me ... it happens on safari, but I'm sure it will happen in other browsers ... my question will be ... why is this happening?

Is there any way to fix this?

Thanks in advance

+5
2

, ,

+6

:

overflow: auto;

CSS div, .

+2

All Articles