Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css margin-top property only works if border is declared [duplicate]

Tags:

html

css

margin

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

like image 341
zanona Avatar asked Feb 17 '11 15:02

zanona


2 Answers

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

like image 188
JamesHalsall Avatar answered Sep 28 '22 01:09

JamesHalsall


If you add:

overflow: auto;

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

like image 23
Shaun Avatar answered Sep 28 '22 01:09

Shaun