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

妖精的绣舞 提交于 2020-01-01 10:56:18

问题


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.



来源:https://stackoverflow.com/questions/5031143/css-margin-top-property-only-works-if-border-is-declared

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!