CSS margin 的奇怪行为,为什么?

发布于 2024-07-22 11:18:23 字数 521 浏览 3 评论 0原文

将 HTML 放在

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <div style="width:400px;height:200px;background-color:Gray;margin-bottom:10px;"></div>
    <div style="width:400px;height:200px;background-color:Green;margin-top:10px;"></div>
</body>
</html>

这两个 DIV 之间的空间下方只有 10 像素。

为什么? 请解释。

Having the HTML below

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <div style="width:400px;height:200px;background-color:Gray;margin-bottom:10px;"></div>
    <div style="width:400px;height:200px;background-color:Green;margin-top:10px;"></div>
</body>
</html>

the space between those two DIVs is only 10 pixels.

Why? Explain please.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

拥抱没勇气 2024-07-29 11:18:23

这种行为称为折叠边距。 不添加保证金值,但使用较高的值:

某些框之间的垂直边距可能会折叠:

  • 正常流中两个或多个相邻的块框垂直边缘会塌陷。 生成的边距宽度是相邻边距宽度的最大值。 […]
  • […]

That behavior is called collapsing margins. The margin values are not added but the higher value is used:

Vertical margins may collapse between certain boxes:

  • Two or more adjoining vertical margins of block boxes in the normal flow collapse. The resulting margin width is the maximum of the adjoining margin widths. […]
  • […]
爱的十字路口 2024-07-29 11:18:23

这是一个很好的边距折叠的解释。 基本上,根据 CSS 规范,所有相邻的边距似乎都会相互折叠,这违反了所有常识。

Here is a good explanation of margin collapsing. Basically, it seems that all adjacent margins will collapse into each other, per the CSS specification and against all common sense.

久随 2024-07-29 11:18:23

如果你想达到想要的效果,你可以使用“padding”代替,边距总是会折叠

if you want to have the desired effect you can use "padding" instead, margins always collapse

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