2016-10-25 95 views
0

我有一個3行的頁面。第一行是150px的固定高度,最後一行是120px的固定高度。我需要中間行根據窗口的高度進行調整,以便所有三行都可見,並且沒有可見的滾動條。中間行必須動態調整,以便即使在加載後,如果將瀏覽器窗口移動到另一個較小的屏幕,中間行也必須相應地進行調整。其次,中間行必須使其內容垂直中間和水平居中。任何幫助表示讚賞。使div動態變化高度

+1

也請發表您的代碼? – prasanth

+0

你可以從'$(window).height()'獲得窗口高度,然後使用'position:fixed; btw'來計算容器的高度,所有主容器都是設計佈局的可怕方法。 – Sojtin

+0

使用100vh從CSS獲得高度比使用JS好得多。你的代碼也依賴Jquery –

回答

2

CSS的高度:

.first-row { 
    height: 150px; 
} 

.middle-row { 
    height: calc(100vh - 150px - 120px); 
} 

.last-row { 
    height: 120px; 
} 
+0

I打算用flexbox製作一支筆,但@Kevin Farrugia打敗了我。使用它比「display:table-cell;」更好。 –

+0

請記住,並不總是支持以下技術: calc:http://caniuse.com/#feat=calc 視口單元:http://caniuse.com/viewport-units/embed/ –

+0

謝謝Ben您的解決方案已運行。現在我該如何垂直對齊中間行內容? –

0

運行在全頁模式的代碼片段(!)。使用css calc函數來自動計算中間容器的高度。

body { 
 
    margin: 0; 
 
} 
 
.top { 
 
    background-color: #f0f0f0; 
 
    height: 150px; 
 
} 
 
.bottom { 
 
    background-color: #ddd; 
 
    height: 120px; 
 
} 
 
.middle { 
 
    background-color: teal; 
 
    display: table-cell; 
 
    height: calc(100vh - 270px); 
 
    text-align: center; 
 
    vertical-align: middle; 
 
    width: 100vw; 
 
}
<div class="top">TOP</div> 
 
<div class="middle">MIDDLE</div> 
 
<div class="bottom">BOTTOM</div>

0

如所建議的,嘗試使用Flexbox的:

<style> 
.container { 
    display: flex; 
    flex-flow: column wrap; 
    align-items: stretch; 
    height: 100%; 
} 
.row{} 
.row.row1{height: 150px;} 
.row.row2{flex: 1 1 auto;} 
.row.row3{height: 120px;} 
</style> 

<div class="container"> 
    <div class="row row1">First row</div> 
    <div class="row row2">Middle row</div> 
    <div class="row row3">Final row</div> 
</div> 

使用此時,不要忘記添加您的供應商前綴。

0

我用flexboxes這些東西:A Complete Guide to Flexbox

.container { 
 
    display: flex; 
 
    flex: 1 1 auto; 
 
    flex-direction: column; 
 
} 
 

 
.header { 
 
    height: 50px; 
 
    background-color: green; 
 
    flex: 0 0; 
 
} 
 

 
.footer { 
 
    height: 30px; 
 
    background-color: red; 
 
    flex: 0 0; 
 
} 
 

 
.content { 
 
    background-color: blue; 
 
    flex: 1 1 auto; 
 
    min-height: 50px; 
 
}
<div class="container"> 
 
    <div class="header"></div> 
 
    <div class="content"></div> 
 
    <div class="footer"></div> 
 
<div>