gpt4 book ai didi

html - 为什么绝对 parent 得到 child 的高度而相对 parent 没有?

转载 作者:可可西里 更新时间:2023-11-01 13:29:13 24 4
gpt4 key购买 nike

我观察到绝对定位的父元素会设置自己的高度来覆盖子元素的行为,而相对定位的父元素则不会。我创建了 2 个 jsfiddles 来模拟这个:

绝对: https://jsfiddle.net/kc1g7v9s/

亲戚: https://jsfiddle.net/smy5q8Ld/

在渲染结果上检查元素时,绝对容器 div 的尺寸为 220x60,而相对容器 div 的尺寸为 689x0。

为什么会这样?我并不是特别想取得任何成就,只是对行为感到好奇。

附加代码:

绝对:

<div class="absolute-container">
<div class="child1"></div>
<div class="child2"></div>
</div>

.child1, .child2 {
width: 100px;
height: 60px;
background-color: grey;
margin-right: 10px;
}
.child1 {
float: left;
}

.child2 {
float: right;
}

.absolute-container {
position: absolute;
clear: both;
}

相对:

<div class="relative-container">
<div class="child1"></div>
<div class="child2"></div>
</div>

.child1, .child2 {
width: 100px;
height: 60px;
background-color: grey;
margin-right: 10px;
}
.child1 {
float: left;
}

.child2 {
float: right;
}

.relative-container {
position: relative;
clear: both;
}

最佳答案

这是因为,正如 this answer 中所解释的那样, 当 calculating the height of "normal" blocks 时 float 被忽略:

Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored […])

enter image description here

position: relative 不会改变这一点。

但是,position: absolute 会生成一个 Block Formatting Context . For those ,

If the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges.

enter image description here

关于html - 为什么绝对 parent 得到 child 的高度而相对 parent 没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685788/

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