2015-09-21 34 views
2

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

回答

2

这是因为,在this answer解释说,花车被忽略时calculating the height of "normal" blocks

在正常流动独生子女考虑在内(即 浮动框和绝对定位框被忽略[...])

enter image description here

而且position: relative不会改变这一点。

但是,position: absolute产生Block Formatting ContextFor those

如果元件具有任何浮动后代,其底部边缘余量是 元素的底部边缘内容下面,则该高度是 增加到包括那些边缘。

enter image description here

+0

有用的链接。非常感谢! – Boyang

相关问题