2011-02-12 80 views
9

我有這樣的簡化的代碼:如何讓DIV填充瀏覽器窗口的剩餘垂直空間?

This is a line of text<br/> 
<div style="background-color: orange; height: 100%">And this is a div</div> 

在div高度最終被瀏覽器窗口客戶端的空間,這總結了與文本行的高度的高度的100%,比窗口高度更,所以你必須滾動。

我該如何製作div高度,所以需要瀏覽器窗口的高度爲減去這行文字?

或者,換句話說,我如何讓div取得所有其他DOM對象已經佔據的所有可用空間?

回答

5

最終,你會想要一個容器。 「overflow:hidden」將隱藏任何溢出容器的東西。如果我們不使用它,那麼我們會看到上面提到的問題:「......超過了窗口高度,所以你必須滾動」。

<div id="container" style="color:white;height:500px;background-color:black;overflow:hidden;"> 
    This is the container 
    <div style="height:100%;background-color:orange;"> 
     This div should take the rest of the height (of the container). 
    </div> 
    </div> 

例具有溢出隱藏:http://jsbin.com/oxico5

例無溢出隱藏:http://jsbin.com/otaru5/2

+2

我喜歡你的方法,因爲它可能是不夠好,模擬OP的要求,但我不知道,如果只能橙色DIV實際上有內容?當容器的白色部分的內容變大時,該內容將被「overflow:hidden」「截斷」...... – Bazzz 2011-02-12 21:20:57

+0

如果內容溢出則不起作用。沒有滾動條和文本從瀏覽器窗口的底部展開。 – sproketboy 2013-02-08 14:23:25

6

我遇到同樣的問題了。這裏是我找到了解決辦法:

<style> 
.container{ 
    position: relative; 
    height: 100%; 
} 
.top-div{ 
    /* height can be here. if you want it*/ 
} 
.content{ 
    position:absolute; 
    left: 0; 
    right: 0; 
    bottom: 0; 
    top: 1em; /* or whatever height of upper div*/ 
    background: red; 
} 
</style> 
<div class="container"> 
    <div class="top-div">This is a line of text</div> 
    <div class="content">And this is a div</div> 
</div> 

源 - http://www.codingforums.com/archive/index.php/t-142757.html

0

這可以很優雅地使用display: table;,而無需知道任何明確的高度值來完成。

演示在這裏:http://codepen.io/shanomurphy/pen/jbPMLX

html, body { 
    height: 100%; // required to make .layout 100% height 
} 

.layout { 
    display: table; 
    width: 100%; 
    height: 100%; 
} 

.layout__row { 
    display: table-row; 
} 

.layout__cell { 
    display: table-cell; 
    vertical-align: middle; 
} 

.layout__cell--last { 
    height: 100%; // force fill remaining vertical space 
} 

<div class="layout"> 
    <div class="layout__row"> 
    <div class="layout__cell"> 
     Row 1 content 
    </div> 
    </div> 
    <div class="layout__row"> 
    <div class="layout__cell layout__cell--last"> 
     Row 2 fills remaining vertical space. 
    </div> 
    </div> 
</div>