带有 margin-top 的项目的边距位于包含框之外

发布于 2024-11-28 00:17:12 字数 371 浏览 5 评论 0原文

我有一些达到此效果的东西:(

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

从来不烧饼 2024-12-05 00:17:12

这与H1标签无关。这就是我们所说的保证金崩溃。

您可以在这里找到有关此主题的帖子:
http://reference.sitepoint.com/css/collapsingmargins

您有多种解决方案:

  • 使用填充代替
  • 添加溢出:自动在您的父div上
  • 添加透明顶部边框到父div

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 :

  • use padding instead
  • add overflow: auto on your parent div
  • add transparent top border to the parent div
酒废 2024-12-05 00:17:12

我通过将所有标题标记 (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.

゛清羽墨安 2024-12-05 00:17:12

尝试添加填充。我以前见过这种问题。如果填充做了同样的事情,那么尝试在周围放置一个容器 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'".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文