你們老是聽到雙飛翼佈局和聖盃佈局...也不知道是誰取的名字,我就叫三欄佈局吧。雖然他們有些細微的區別,但本質上都是實現一個三欄佈局,即左右兩欄固定,中間自適應。瀏覽器
網上隨便一搜,全是實現方案,少到兩三種,多到七八種。各類方法都有優缺點,但我以爲比較實用的方法主要就那三四種,由於不少方法實際上是被淘汰的或者說太麻煩(如表格佈局)。佈局
實現思路:
先將左右兩欄進行浮動,左邊欄向左浮動,右邊欄向右浮動就能固定在兩邊。可是要注意一點,這種方法要將中間欄放在最後,由於若是將中間欄放在中間,而且沒有對自身進行浮動的話,會佔據文檔中的位置,致使右邊欄並不能徹底和左邊欄平齊。flex
HTML:spa
<!-- 三欄佈局 浮動定位--> <div class="layout"> <header>頭部</header> <main> <div class="left">左邊欄</div> <div class="right">右邊欄</div> <div class="center">中間欄</div> </main> <footer>底部</footer> </div> <!-- 三欄佈局 浮動定位-->
SCSS:code
//浮動佈局 .layout { color:white; text-align: center; height: 100%; overflow: hidden; header,footer{ width: 100%; height: 70px; background: rgb(202,132,2); } footer { position: absolute; bottom: 0; } main { width: 100%; height: 100%; background: red; .left,.right { width: 300px; height: 100%; background: rgb(14, 214, 171); } .left { float:left; } .right{ float:right; } .center { height:100%; background: rgb(26, 26, 122); } } }
效果:ip
缺點:
浮動元素會脫離文檔流,若是在<main>
的內部還有其餘元素,有可能會由於父元素的高度塌陷而致使問題。因此要麼給父元素設置高度,要麼就要清除浮動了。文檔
實現思路:
將左右兩欄進行絕對定位,固定在左右兩邊,中間欄經過左右margin距離來適應寬度。一樣,這種方法要注意中間欄在HTML結構中的位置,若是中間欄在中間,那麼中間欄也要進行絕對定位,若是在最後面則不須要進行絕對定位。it
HTML:io
<!-- 三欄佈局 絕對定位--> <div class="layout"> <header>絕對定位方案</header> <main> <div class="left">左邊欄</div> <div class="right">右邊欄</div> <div class="center">中間欄</div> </main> <footer>底部</footer> </div> <!-- 三欄佈局 絕對定位-->
SCSS:class
// 絕對定位佈局 .layout { color:white; text-align: center; height: 100%; overflow: hidden; header,footer{ width: 100%; height: 60px; background: rgb(202,132,2); } footer { position: absolute; bottom: 0; } main { width: 100%; height: 100%; background: red; position: relative; .left,.right{ position: absolute; width: 300px; height: 100%; background: rgba(100, 96, 87,0.5); } .left { left:0 } .right { right:0; //top:0; } .center { height: 100%; margin:auto 300px; left:0; right:0; background: blue; } } }
效果:
缺點:
絕對定位一樣會脫離文檔流,若是其餘元素位置有要求的話,須要繼續設置定位。
實現思路:
彈性佈局十分簡單,給最外層的父級元素設置爲彈性盒子,而後設置兩端對齊,中間欄的寬度設爲100%便可。
HTML:
<!-- 三欄佈局 flex佈局--> <div class="layout"> <header>flex方案</header> <main> <div class="left">左邊欄</div> <div class="center">中間欄</div> <div class="right">右邊欄</div> </main> <footer>底部</footer> </div> <!-- 三欄佈局 flex佈局-->
SCSS:
//flex佈局 .layout { color:white; text-align: center; height: 100%; overflow: hidden; header,footer{ width: 100%; height: 60px; background: rgb(202,132,2); text-align: center; } footer { position: absolute; bottom: 0; } main { width: 100%; height: 100%; background: red; display:flex; justify-content: space-between; .left,.right { width: 300px; height: 100%; background: rgb(18, 157, 167); } .center { width: 100%; height:100%; background: blue; } } }
效果:
缺點:flex是CSS3纔有的,瀏覽器兼容性最低到IE8。