初始時,多個列內容大小不一樣,高度不一樣。如今須要設置不一樣的背景來顯示,並且各個列的高度須要保持一致。那麼這就須要利用到多列等高佈局。
最終須要的效果:
css
技術點:彈性盒子佈局flex,默認值就是自帶等高佈局的特色。html
定義flex佈局的時候,有一些默認值。git
flex-direction
屬性定義主軸的方向。默認值爲row
,通常是水平顯示。flex容器的主軸被定義爲與文本方向相同。 主軸起點和主軸終點與內容方向相同。github
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.flex
技術點:table佈局自然就具備等高的特性。ui
display設置爲table-cell
,則此元素會做爲一個表格單元格顯示。相似於使用標籤<td>
或者<th>
。code
HTML結構htm
<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.
實現:設置父容器的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.
技術點: 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源碼 [完]