gpt4 book ai didi

html - 嵌套 div 中的垂直边距未按预期工作

转载 作者:行者123 更新时间:2023-11-28 10:39:22 24 4
gpt4 key购买 nike

为什么内容 div 的边距也压低了 intro div?我觉得我在嵌套 div 时犯了一个非常愚蠢的错误,但我真的不知道。

body {
margin: 0px;
}
div.content {
text-align: center;
margin-top: 35px;
border-style: solid;
}
h1 {
display: inline-block;
margin: auto;
font-family: Lane;
color: white;
font-size: 80px;
}
div#intro {
background: blue;
height: 100%;
width: 100%;
}
<div id=intro>
<div class=content>
<h1>Text</h1>
</div>
</div>

最佳答案

发生这种情况是因为垂直 margins are collapsing .

Box Model 8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins' widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

看看 relevant spec查看适用于所有可能解决方法的规则。

例如,一个规则是:

Margins of elements that establish new block formatting contexts (such as floats and elements with overflow other than visible) do not collapse with their in-flow children.

因此,在您的情况下,您只需将 #intro 元素上的 overflow 属性更改为默认值 visible 以外的值>。 auto/hidden 等值可以工作:

body {
margin: 0px;
}
div#intro {
background: blue;
height: 100%;
width: 100%;
overflow: auto;
}
div.content {
text-align: center;
margin-top: 35px;
border-style: solid;
}
h1 {
display: inline-block;
margin: auto;
font-family: Lane;
color: white;
font-size: 80px;
}
<div id=intro>
<div class=content>
<h1>Text</h1>
</div>
</div>

关于html - 嵌套 div 中的垂直边距未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com