【问题标题】:Why absolute parent get child height while relative parent doesn't?为什么绝对父母得到孩子身高,而相对父母没有?
【发布时间】:2015-09-21 00:39:51
【问题描述】:

我观察到绝对定位的父级会设置自己的高度以覆盖子元素,而相对定位的父级不会。我创建了 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;
}

【问题讨论】:

    标签: html css position css-position


    【解决方案1】:

    这是因为,正如 this answer 中所解释的,当 calculating the height of "normal" blocks 时,浮点数会被忽略:

    只考虑正常流程中的孩子(即, 浮动框和绝对定位框被忽略 […])

    position: relative 并没有改变这一点。

    但是,position: absolute 会生成 Block Formatting ContextFor those,

    如果元素有任何浮动后代,其下边距边缘 低于元素的底部内容边缘,则高度为 增加以包括这些边缘。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 2014-08-27
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多