初始時,多個列內容大小不同,高度不同。現在需要設置不同的背景來顯示,而且各個列的高度需要保持一致。那么這就需要利用到多列等高布局。
最終需要的效果:
1. 真實等高布局 flex
技術點:彈性盒子布局flex,默認值就是自帶等高布局的特點。
定義flex布局的時候,有一些默認值。
flex-direction
屬性定義主軸的方向。默認值為row
,一般是水平顯示。flex容器的主軸被定義為與文本方向相同。 主軸起點和主軸終點與內容方向相同。
align-item
屬性定義flex子項在flex容器的當前行的側軸(縱軸 或者說 交叉軸)方向上的對齊方式。默認值為 stretch
,元素被拉伸以適應容器。
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
css
.box {
display: flex;
}
.left {
width: 300px;
background-color: grey;
}
.center {
flex: 1;
background: red;
}
.right {
width: 500px;
background: yellow;
}
See the Pen equal-hight-layout-flex by weiqinl (@weiqinl) on CodePen.
2. 真實等高布局 table-cell
技術點:table布局天然就具有等高的特性。
display設置為table-cell
,則此元素會作為一個表格單元格顯示。類似於使用標簽<td>
或者<th>
。
HTML結構
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
CSS樣式
.left {
display: table-cell;
width:30%;
background-color: greenyellow;
}
.center {
display: table-cell;
width:30%;
background-color: gray;
}
.right {
display: table-cell;
width:30%;
background-color: yellowgreen;
}
See the Pen equal-hight-layout-table by weiqinl(@weiqinl) on CodePen.
3. 假等高列布局 內外邊距底部正負值
實現:設置父容器的overflow屬性為hidden。給每列設置比較大的底內邊距,然后用數值相似的負外邊距消除這個高度。
-
不考慮可擴展性,只需要將padding-bottom/margin-bottom ,設置為最高列與最低列相差高度值,就可以得到等高效果。
-
考慮擴展性,為了防止將來可能某列高度大量的增加或減少,所有,我們設置了一個比較大的值。
技術點
-
background 會填充內邊距 padding,而不會填充外邊距 margin 。margin具有坍塌性,可以設置負值。
-
float:left。使用float,元素會脫離文檔流,使其浮動至最近的文檔流元素。在這里的作用是,將三個div元素並排。
-
overflow:hidden; 設置overflow屬性為hidden,這樣會讓父容器產生BFC(Block Fromatting Context塊級格式化上下文)效果,消除float帶來的影響。同時,根據需要,會截取內容以適應填充框,將超出容器的部分隱藏。
HTML結構
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
CSS
.box {
overflow: hidden;
}
.box > div{
/**
* padding-bottom 設置比較大的正值。
* margin-bottom 設置絕對值大的負值。
**/
padding-bottom: 10000px;
margin-bottom: -10000px;
float:left;
width:30%;
}
.left {
background-color: greenyellow;
}
.center {
background-color: gray;
}
.right {
background-color: yellowgreen;
}
See the Pen equal-height-layout-padding-margin-bottom by weiqinl(@weiqinl) on CodePen.
4. 假等高布局,背景視覺效果
**技術點: float浮動,並設置每一列的寬度。設置父元素為行內塊級元素,之后再利用線性漸變的圖片來設置父元素的背景凸顯等高的效果 **
CSS linear-gradient
函數用於創建一個表示兩種或多種顏色線性漸變的圖片。
display: inline-block
,設置為行內塊級元素。
<div class="box five-columns">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
css
/** 需要自己算出平均每列的寬度 */
.box {
display: inline-block;
background: linear-gradient(
to right,
red,
red 20%,
blue 20%,
blue 40%,
yellow 40%,
yellow 60%,
orange 60%,
orange 80%,
grey 80%,
grey);
}
.col {
float: left;
width: 16%;
padding: 2%;
}
See the Pen equal-height-layout-float-fluid-width by weiqinl (@weiqinl) on CodePen.
github源碼
[完]