2014-03-19 28 views
1

我有一個div結構這樣,爲什麼股利不走剩餘空間

<div style="height:100%"> 
    <div style="height:50px"></div> 
    <div id="auto" style="height:100%"></div> 
</div> 

但好像id="auto"走的是高度爲其父身高和父溢出。可以設置css的方式0123'div取父母的剩餘高度? 我想要做的是讓id=auto股利承擔母公司div大小的其餘部分。

這裏是jsFiddle

回答

2

這是因爲height屬性的百分比值是相對於包含框的塊的高度而言的。因此100%意味着整個高度。

10.5 Content height: the 'height' property

指定的百分比高度。百分比的計算方法爲 尊重所生成框的高度containing block。如果未明確指定包含塊的高度 (即,其 取決於內容高度),並且該元素不是絕對 定位,則該值計算爲'auto'。 root element上的百分比高度相對於initial containing block

一個解決辦法是使用負餘量爲第二<div>元件以除去srcollbar,然後加入position: relative;到第一個,使其回到在第二一個的頂部。

在這種情況下,我們應該使用padding第二DIV的頂部,以推動其內容下來,也是爲了增加box-sizing: border-box計算包括填充邊界框的高度:

Example Here

<div class="parent"> 
    <div class="top"></div> 
    <div class="content"></div> 
</div> 
.parent { height:100%; } 

.top { 
    height: 100px; 
    position: relative; 
} 

.content { 
    background-color: gold; 
    min-height: 100%; 

    margin-top: -100px; /* equals to the height of .top element */ 
    padding-top: 100px; /* equals to the height of .top element */ 

    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
} 

值得注意的是,這種方法would work on IE8+


時下所有主流瀏覽器都支持box-sizing: border-box,但是你用隔離元件代替padding + box-sizing.content下的內容:

Example Here

<div class="content"> 
    <div class="spacer"></div> 
    <!-- content goes here -->. 
</div> 
.spacer, .top { 
    height: 100px; 
} 

這種方法將上工作IE 6/7 +(*)


或者,也可以嵌套在.content.top元件和丟棄.parent在爲了達到同樣的效果正在處理中IE 6/7 +(*)

Example Here

<div class="content"> 
    <div class="top"></div> 
    <div class="inner"> 
     <!-- content goes here --> 
    </div> 
</div> 

(*)IE6 +通過使用height屬性,IE7 +通過使用min-height

1

如果您不需要支持IE8或IE9,使用CSS鈣(http://caniuse.com/calc

<div style="height:100%"> 
    <div style="height:50px"></div> 
    <div id="auto" style="height:calc(100%-50px);"></div> 
</div> 

如果你需要支持舊的IE瀏覽器的話,我會建議使用display:table,display:table-cell和display:table-row。使用桌面顯示器時要記住很多小怪癖,所以如果可能的話,堅持使用calc。

1

可以達到預期的效果,如果你能絕對定位的第一個孩子的div(一個是100個像素高):

演示:http://jsfiddle.net/rn2Xe/2/

<div style="height:100%; padding-top:100px; box-sizing: border-box; position: relative;"> 
    <div style="height:100px; position: absolute; top: 0; width: 100%; box-sizing: border-box;"></div> 
    <div style="height:100%;"></div> 
</div> 

注意:使用類CSS 。你的代碼可能是很多更清潔。

1

你也許可以用css calc來解決這個問題,但是如果你想要很好的遺留支持,可以使用表格。