我們畫頁(yè)面的時(shí)候有可能遇到一種情況,一上一下兩個(gè)元素,其中一個(gè)固定高度,然后我們希望另一個(gè)占據(jù)縱向所有剩余的高度。因?yàn)楦叨饶J(rèn)是以實(shí)際容器內(nèi)內(nèi)容高度為準(zhǔn)的,也就是說默認(rèn)情況下我們的元素不會(huì)在內(nèi)容不足的情況下自動(dòng)撐開高度占滿空間
本文中元素位置如下,不做特殊說明的話本文的html結(jié)構(gòu)不會(huì)有變化
<div class="outside-box">
<div class="top-box">這里是一個(gè)固定高度的組件, height: 100px;</div>
<div class="bottom-box">這是不定高度的組件</div>
</div>
當(dāng)前的CSS如下
.outside-box{
width: 200px;
height: 100vh;
background-color: #eee;
}
.top-box{
height: 100px;
background-color: #ddd;
}
.bottom-box{
background-color: #ccc;
}
當(dāng)前的頁(yè)面效果如下

【背景顏色是特地加的方便大家看清】
現(xiàn)在我們需要將那個(gè)不定高度的組件的高度撐開,占滿縱向剩余的空間,要怎么做呢?
我這里提供兩種做法
calc
我們可以用calc實(shí)時(shí)計(jì)算不定高度組件的高度
.bottom-box{
height: calc(100% - 100px);
background-color: #ccc;
}
效果如下

可以看到下面的不定高度組件的高度撐開占滿了剩余的空間
但是calc是實(shí)時(shí)計(jì)算,性能不是特別好,大家慎用
flex
我們也可以使用flex來(lái)實(shí)現(xiàn)
父組件要設(shè)置為flex,且設(shè)為縱向排布,然后子組件用flex-grow: 1占據(jù)所有剩余空間
.outside-box{
width: 200px;
height: 100vh;
display: flex;
flex-direction: column;
background-color: #eee;
}
.bottom-box{
flex-grow: 1;
background-color: #ccc;
}
效果如下

可以看到,不定高度的組件也是撐開高度占據(jù)了剩余空間
應(yīng)該說,flex-grow這個(gè)屬性,能夠決定剩余空間的分配,他會(huì)將所有剩余空間在所有有這個(gè)屬性的元素之間進(jìn)行分配,分配的比例就是各組件該屬性值占所有組件該屬性值總和的比例
比如我再加第三個(gè)組件在下面,并設(shè)置flex-grow為2,這時(shí)就會(huì)有兩個(gè)元素帶有該屬性,且屬性值總和為3,則此時(shí),中間的組件【flex-grow值為1】會(huì)占據(jù)三分之一的空間,下面的組件【flex-grow值為2】會(huì)占據(jù)三分之二的空間
具體如下
<div class="outside-box">
<div class="top-box">這里是一個(gè)固定高度的組件, height: 100px;</div>
<div class="bottom-box">這是不定高度的組件</div>
<div class="box3">這是第三個(gè)組件</div>
</div>
<style>
.outside-box{
width: 200px;
height: 100vh;
display: flex;
flex-direction: column;
background-color: #eee;
}
.top-box{
height: 100px;
background-color: #ddd;
}
.bottom-box{
flex-grow: 1;
background-color: #ccc;
}
.box3{
flex-grow: 2;
}
</style>
效果如下圖

其他
我這個(gè)時(shí)候又想了,那我如果在第一個(gè)元素上面加flex-grow屬性會(huì)怎么樣
于是我將第一個(gè)元素的flex-grow設(shè)為10
親測(cè)沒有任何事情發(fā)生
所以,直接寫明的height屬性會(huì)覆蓋flex-grow屬性的效果,當(dāng)有height又有flex-grow時(shí),flex-grow屬性會(huì)直接失效,甚至不參與flex-grow屬性值總數(shù)的統(tǒng)計(jì)
而flex-grow屬性的效果不會(huì)擠占已有明確高度/寬度設(shè)置的元素占據(jù)的空間
最后貼上完整代碼,大家有需要的話自己拿去試試
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.outside-box{
width: 200px;
height: 100vh;
display: flex;
flex-direction: column;
flex-grow: 10;
background-color: #eee;
}
.top-box{
height: 100px;
background-color: #ddd;
}
.bottom-box{
flex-grow: 1;
background-color: #ccc;
}
.box3{
flex-grow: 2;
}
</style>
</head>
<body>
<div class="outside-box">
<div class="top-box">這里是一個(gè)固定高度的組件, height: 100px;</div>
<div class="bottom-box">這是不定高度的組件</div>
<div class="box3">這是第三個(gè)組件</div>
</div>
</body>
</html>