2015-09-21 35 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

相關問題