为什么这个 div 的 margin-top 属性没有按照预期工作?

3
我正在使用Firefox 8.0.1浏览器。

margin-top属性的效果不如预期,有谁能帮忙解决吗?谢谢。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
          <title>New Border</title>

          <style type="text/css">
               #page {
                    width:980px;
                    margin: 50px auto;
               }

               #board {
                    width:600px;
                    height:400px;
                    background-color: gray;
               }

               .cell {
                    border: 1px solid;
                    width:50px;
                    height:20px;
                    margin: 30px 5px;
               } 
          </style>
     </head>
     <body>
          <div id="page">
               <div id="board">
                    <div class="cell">
                    </div>
               </div>
          </div>
     </body>
</html>

所以,在cell div中的margin-top没有按预期工作。 我认为应该使用margin-left将cell div放在board div下面,但实际上不是这样。 这是屏幕截图: enter image description here

我发现这个方法可行:向容器元素添加padding-top或border-top样式将解决该问题。http://www.blog.highub.com/css/css-hacks/css-firefox-top-margin-extra-space/ - hetaoblog
这被称为折叠外边距,请查看 http://www.w3.org/TR/CSS21/box.html#collapsing-margins 和http://reference.sitepoint.com/css/collapsingmargins。 - sandeep
3个回答

7

您可以添加

overflow:hidden;

或者

border:1px solid rgba(0,0,0,0); /*or*/ border:1px solid transparent;

转到 #board 的 css。
查看 http://jsfiddle.net/3QfWS/

1
谢谢,你能谈谈背后的原因吗? - hetaoblog
嗯,我真的不知道为什么这个 div 超出了它的容器。这种情况经常发生在我身上,我猜通过添加边框或者使用 overflow:hidden 可以帮助浏览器理解嵌套的 div 不应该超出它的容器。 - XCS
2
@hetaoblog 的原因是 http://www.w3.org/TR/CSS21/box.html#collapsing-margins。 - Boris Zbarsky

0

我在父元素中添加了“clearfix”类,这为我解决了问题。


-1

你在board div中嵌套了cell。如果你想要它在下面,就把它放到外面。


好的,我的意思是,margin-top被设置为30px,但是没有显示出有30px的margin-top,对吧?那为什么会这样呢? - hetaoblog
不确定为什么我的答案会被打分降低。您的问题不太清楚。如果您想要它在那个 div 中,您可以尝试添加一些 padding。 - simonmorley
好的,我没有做“标记”。 - hetaoblog
我知道你没有尝试过。你试过填充吗?或者上面提到的溢出建议。应该可以解决问题。 - simonmorley
是的,添加 padding-top 或 border-top 将使其正常工作。谢谢。 - hetaoblog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接