前言:本文介紹五種常見的三列布局,主要是兩側定寬,中間自適應,其他情況大同小異。
方式一:float
HTML程式碼:
<div class="layout-float">
<div class="left">左邊</div> <div class="right">右邊</div>
<div class="center">中間</div>
</div>
注:center要放最後。center這個元素是塊級元素,佔據一行,如果center放中間,right元素會在下一行向右浮動
CSS程式碼:
<style> .left { float: left; width: 300px; background-color: blue; } .right { float: right; width: 300px; background-color: blue; } .center { background-color: red; } </style>
方式二:table佈局,非HTML中<table>標籤
HTML程式碼:
<div class="layout-table"> <div class="left"></div> <div class="center">這是中間</div> <div class="right"></div> </div>
CSS程式碼:
<style> .layout-table{ width: 100%; display: table; height: 100px; } .layout-table div { display: table-cell; } .left { width: 300px; background-color: blue; } .right { width: 300px; background-color: red; } .center { background-color: blue; } </style>
方式三:flex佈局
HTML程式碼:
<div class="layout-flexbox"> <div class="left"></div> <div class="center">這是中間</div> <div class="right"></div> </div>
CSS程式碼:
<style> .layout-flexbox{ display: flex; } .left { width: 300px; background-color: blue; } .center { flex: 1; background-color: green; } .right { width: 300px; background-color: blue; } </style>
方式四:grid佈局
HTML程式碼:
<div class="layout-grid"> <div class="left"></div> <div class="center">這是中間</div> <div class="right"></div> </div>
CSS程式碼:
<style> .layout-grid{ display: grid; width:100%; grid-template-rows:100px; grid-template-colums:300px auto 300px; } .left { background-color: blue; } .center { background-color: green; } .right { background-color: blue; } </style>
方式五:絕對佈局
HTML程式碼:
<div class="layout-absolute"> <div class="left"></div> <div class="center">這是中間</div> <div class="right"></div> </div>
CSS程式碼:
<style> .layout-absolute div{ position: absolute; } .left { left:0; width:300px; background-color: blue; } .center { left:300px; right:300px; background-color: green; } .right { width:300px; right:0; background-color: blue; } </style>
五種方法的優缺點:
float:相容性較好,一般需要清除浮動
table:相容性較好,SEO不太友好
grid:新技術,對舊瀏覽器相容不太好,程式碼簡潔
absolute:方便易用,脫離文件流,可使用性較差
flex:沒什麼明顯缺點,且移動端友好