带有 margin-top 的项目的边距位于包含框之外
我有一些达到此效果的东西:(
#div {
background: green;
width: 200px;
height: 100px;
}
h1 {
margin-top: 100px;
}
显然有一些 HTML 与之配合。)
现在,当在浏览器中查看时,h1
显示在 #div
的最顶部> 且 100px
边距位于 #div
之上。
谁能提出一个理由吗?
(代码有点太复杂,无法插入相关部分,所以如果没有人能给我答案,那么我会将其发布,也许有人会发现错误或其他内容。)
I have something to this effect:
#div {
background: green;
width: 200px;
height: 100px;
}
h1 {
margin-top: 100px;
}
(And obviously there is some HTML to go with it.)
Now when viewed in the browser the h1
shows at the very top of the #div
and the 100px
margin goes on top of the #div
.
Can anyone suggest a reason?
(The code is a little too complicated to insert the relevant parts so if no-one can give me an answer then I will post it and maybe someone will spot an error or something.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与H1标签无关。这就是我们所说的保证金崩溃。
您可以在这里找到有关此主题的帖子:
http://reference.sitepoint.com/css/collapsingmargins
您有多种解决方案:
This is not related to the H1 tag. This is what we call margin collapse.
You can find a post about this subject here :
http://reference.sitepoint.com/css/collapsingmargins
you have several solutions :
我通过将所有标题标记 (h1-h6)
display: inline-block;
解决了这个问题。作为带边距的内联元素,它们可能会像这样溢出,但作为内联块,它们与其他元素的表现要好一些。I was able to solve this problem by making all of my header tags (h1-h6)
display: inline-block;
. As inline elements with margins, they can overflow like that, but as inline blocks they behave a little more nicely with others.尝试添加填充。我以前见过这种问题。如果填充做了同样的事情,那么尝试在周围放置一个容器 div,但 #div 和 h1 然后添加边距。如果您只是想将 h1 从 #div 向下移动,那么填充是您最好的选择,因为它会“将 h1 进一步推入 #div '框'”。
Try to add padding instead. I've seen this kind of problem before. If the padding does the the same thing then try putting a container div around but #div and the h1 then add the margin. If you are just wanting to move the h1 down from the #div then padding is your best bet since it will "Push the h1 further into the #div 'box'".