前言
以下五種方法都可以實現三欄佈局,效果如下:
也可以自己調節屬性參數,獲得四欄、五欄等效果,或者是自己想要的寬度。
1、漂移佈局
-
html
<div class="left-center-right"> <div class="left">左邊</div> <!-- 右欄部分要寫在中間內容之前 --> <div class="right">右邊</div> <div class="center">中間</div> </div>
注意:右欄部分要寫在中間內容之前。
-
css
.left-center-right>div { height: 150px; } .left { float: left; width: 300px; background: red; } .center { background: yellow; } .right { float: right; width: 300px; background: blue; }
2、絕對佈局
-
html
<div class="left-center-right"> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div> </div>
因爲是絕對佈局,所以這裏三欄的順序沒有要求。
-
css
.left-center-right>div { position: absolute; height: 150px; } .left { left: 0; width: 300px; background: red; } .center { /* 離左右各三百 */ right: 300px; left: 300px; background: yellow; } .right { right: 0; width: 300px; background: blue; }
3、flex佈局
-
html
<div class="left-center-right"> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div> </div>
-
css
.left-center-right { display: flex; } .left-center-right>div { height: 150px; } .left { flex: 1; background: red; } .center { flex: 2; background: yellow; } .right { flex: 1; background: blue; }
採用flex佈局的元素,稱爲flex容器,簡稱"容器"。它的所有子元素自動成爲容器成員,稱爲flex項目(flex item),簡稱"項目"。
把left-center-right設置爲flex容器後,left、center和right就自動成爲容器成員。
設置flex:1說明該容器成員的寬度佔flex容器寬度的一份,flex:2說明該容器成員的寬度佔flex容器寬度的兩份。比如上面的css的容器成員一共設置了4份flex,所以left的寬度就佔flex容器寬度的1/4,center佔1/2,right佔1/4。
4、表格佈局
-
html
<div class="left-center-right"> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div> </div>
-
css
.left-center-right { display: table; height: 150px; width: 100%; } .left-center-right>div { display: table-cell; } .left { width: 300px; background: red; } .center { background: yellow; } .right { width: 300px; background: blue; }
5、網格佈局
-
html
<div class="left-center-right"> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div> </div>
-
css
.left-center-right { display: grid; /* 行寬 */ grid-template-columns: 300px auto 300px; /* 行高 */ grid-template-rows: 150px } .left { background: red; } .center { background: yellow; } .right { background: blue; }