2017-06-06 251 views
1

我在裏面有內容的div。2元素填充剩餘高度

我希望頂部和底部的div填補餘下的空間。

喜歡的東西this

<div class="container"> 
    <div class="top"> 

    </div> 
    <div class="middle"> 
     Content 
    </div> 
    <div class="bottom"> 

    </div> 
</div> 

如果可能的話我想設定最低高度的頂部和底部的容器。

回答

1

藉助Flexbox,就可以做這

html, body { 
 
    margin: 0; 
 
} 
 
body { 
 
    display: flex;   /* IE fix */ 
 
} 
 
.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    min-height: 100vh; 
 
    width: 100%;    /* IE fix */ 
 
} 
 
.top, .bottom { 
 
    flex: 1;     /* fill remaining space */ 
 
    background: lightblue; 
 
} 
 
.middle { 
 
    background: lightgreen; 
 
}
<div class="container"> 
 
    <div class="top"> 
 

 
    </div> 
 
    <div class="middle"> 
 
     Content 
 
    </div> 
 
    <div class="bottom"> 
 

 
    </div> 
 
</div>


如果你需要,你還可以添加一個min-heighttop/bottom元素

html, body { 
 
    margin: 0; 
 
} 
 
body { 
 
    display: flex;   /* IE fix */ 
 
} 
 
.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    min-height: 100vh; 
 
    width: 100%;    /* IE fix */ 
 
} 
 
.top, .bottom { 
 
    flex: 1;     /* fill remaining space */ 
 
    background: lightblue; 
 
    min-height: 200px;  /* set a min-height */ 
 
} 
 
.middle { 
 
    background: lightgreen; 
 
}
<div class="container"> 
 
    <div class="top"> 
 

 
    </div> 
 
    <div class="middle"> 
 
     Content 
 
    </div> 
 
    <div class="bottom"> 
 

 
    </div> 
 
</div>

+0

偉大的迴應,這似乎正是我需要感謝! – KevinKelbie

+0

@WizardCoder我知道你沒有說它是壞的,但再次看看,IE10支持2012年的Flexbox語法,它在上面的代碼中是'display:-ms-flexbox;','-ms-flex-direction :列'和'-ms-flex:1;' – LGSon

0

.top{ 
 
min-height:100px; 
 
} 
 
.bottom{ 
 
min-height:100px; 
 
}

,或者你可以使用不同的meseurment - 像VH - 的觀點高度等 忘了補充 - 它會進入你的CSS文件

+0

但這不會填充剩餘空間。 – KevinKelbie

+0

你想使用jQuery嗎?你需要使用動態計算,如果是的話,我可以告訴你簡短的jQuery功能,可以幫助你 –

+0

當然,如果這是最簡單的方法。謝謝您的幫助! :) – KevinKelbie

0

這裏是你較真表的解決方案。

html, body { 
 
    margin: 0; 
 
    height:100%; 
 
} 
 
.container { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
.container > div { 
 
    display: table-row; 
 
} 
 
.table-cell { 
 
    display: table-cell; 
 
} 
 
.top, .bottom { 
 
    background: #ADD8E6; 
 
} 
 
.middle { 
 
    background: #90EE90; 
 
    height:1px; 
 
}
<div class="container"> 
 
    <div class="top"> 
 
    <div class="table-cell"> 
 

 
    </div> 
 
    </div> 
 
    <div class="middle"> 
 
    <div class="table-cell"> 
 
     Content 
 
    </div> 
 
    </div> 
 
    <div class="bottom"> 
 
    <div class="table-cell"> 
 

 
    </div> 
 
    </div> 
 
</div>

+0

另一個偉大的解決方案謝謝!這比柔性解決方案更友好嗎? – KevinKelbie

+0

不使用flexbox的唯一原因是如果你想支持IE9。同樣在具有複雜結構的大型網站上,flexbox可以稍微增加頁面加載時間。我個人只有在沒有其他方法來實現我想要的佈局時才使用flexbox。所有人都說,在這種情況下,我看不到使用flex的任何問題。 – WizardCoder