2014-03-30 88 views
3

我想要一個身高的孩子元素:100%;容器適用高度:100%;.當出現文檔類型時,這似乎失敗了。最小高度的孩子:100%不適用身高:100%

如果您使用最小高度:100%;對於父母,子元素不適用高度:100%;.

如果您使用身高:100%;子元素會伸展,但會使父元素溢出。 如果您然後嘗試使用高度:100%;在父母身上並保持最小身高:100%;對孩子來說,孩子們不會再舒展了。

這裏有一個小例子:

<!DOCTYPE html> 
<html> 
<head> 
<title>Oh Well</title> 
<style> 
html, body { 
    width: 100%; 
    height:100%; 
    background: white; 
    margin:0; 
    padding:0; 
} 

#min-h-100 { 
    background-color: #eee; 
    min-height: 100%; 
} 
#min-h-100 > div{ 
    min-height: 100%; 
} 

#h-100 { 
    background-color: #ccc; 
    height: 100%; 
} 
#h-100 > div { 
    height: 100%; 
} 
</style> 
</head> 
<body> 
<div id="min-h-100"> 
    <div>If this is heigher than the container, the container expands.</div> 
    <div>The child elements do not get 100% height.</div> 
</div> 
<div id="h-100"> 
    <div>The child elements get 100% height.</div> 
    <div>But there will be an overflow.</div> 
</div> 
<div>THIS SHOULD BE PUSHED DOWN</div> 
</body> 
</html> 

編輯: 最小高度不繼承。 @Cryrillus提出了將display:table應用到父項的想法,該項至少延伸了父項。 @Volker E.創建了一個codepen

編輯: 如果你不想支持IE≤8,您可以設置孩子最小高度:100vh;這將使其至少與視口一樣高。

+2

最小高度不能通過最小高度而不受任何其他規則無法估計。 A **規則僅繼承父母 –

+0

@Gyryrillus中的類似規則**,這就是爲什麼min-height不起作用,謝謝:)。有沒有辦法來防止溢出,或者更確切地說,在使用height時拉伸父項:100%;? – aimed

+2

你可以嘗試給所有孩子發送'height:100%'並使用'display:table',所以它可以讓它們伸展,你也需要設置'width'然後 –

回答

1

我覺得這個問題很有趣,特別是情況#2與id="h-100"意味着幾個height: 100%孩子height: 100%父母。我想出了Codepen including the different options。 爲防止第二種情況發生溢出,您也可以使用overflow: hidden,但這會造成信息丟失。

@GCyrillus說得對,請使用display: table;display: table-row/table-cell;符合兒童div s。

#h-100-table { 
    background-color: #ddd; 
    display: table; 
    width: 100%; 
    height: 100%; 
} 
#h-100-table > div { 
    display: table-row; 
    width: 100%; 
} 
#h-100-table > div > div { // you don't need to go for extra nesting, but it's clearer. 
    display: table-cell; 
    width: 100%; 
} 

#h-100-table的盛大孩子不是必需的,它更可維護性。你也可以只與table-row孩子一起去。

+0

@GCyrillus與您的方法父母拉伸,但第二個孩子似乎只顯示非空白區域。 – aimed

1

如果你不想支持IE≤8,你可以設置子min-height:100vh;這將使它至少與視口一樣高(基本上給你所需的效果)。 (seen here