CSS三列布局之左右寬度固定,中間元素自適應問題,css三列
最近學到了幾種關於左右固定寬度,中間自適應的三列布局的方法,整理了一下,在這裡跟大家一起分享分享,其中有什麼不足的還望各位給指導指導哈。首先我想到的是float——浮動布局
使用浮動,先渲染左右兩個元素,分別讓他們左右浮動,然後再渲染中間元素,設定它的margin左右邊距分別為左右兩個元素的寬度。例如以下代碼就可以實現我們想要的三列效果啦。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <div style="width:300px; float:left; background:#6FF">左側的內容 固定寬度</div> <div style="width:200px; float:right; background-color:#960">右側的內容 固定寬度</div> <div style="margin-left:300px;margin-right:200px; background-color:#9F3;">中間內容,自適應寬度</div></body></html>
其次我想到了position——定位
使用定位方式,不需要先渲染中間元素,只要把左右兩個元素分別使用定位,left:0;right:0;中間元素設定margin左右邊距為左右兩個元素的寬度即可。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style>.left{ width:200px; height:500px; position: absolute; top:0; left:0; background:blue;}.center{ margin-left: 200px; margin-right: 300px; height:500px; background-color: green;}.right{width:300px;height:500px;position: absolute;;top:0;right:0;background: blue;} </style></head><body> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div></body></html>
第三、使用雙飛翼布局
使用雙飛翼布局與其他方式不同,它最先渲染的是中間元素,然後才渲染兩邊元素(注意,這一點與float布局方式正好相反喲),先將三個元素都設定為向左浮動,然後使用負邊距將左右兩個元素覆蓋到中間元素的左右兩邊,形成羽翼。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style>.middle{ float: left; width: 100%; height: 50px; background-color: #fff9ca;}.middle-wrap{ margin: 0 200px 0 150px;}.left{ float: left; width: 150px; height: 50px; background-color: red; margin-left: -100%; /*負邊距的作用就是讓左邊div蓋在中間div上面*/}.right{ float: left; width: 200px; height: 50px; background-color: yellow; margin-left: -200px; /*讓右邊的div覆蓋在中間的div右邊*/} </style></head><body> <div class="middle"> <div class="middle-wrap">middle</div> </div> <div class="left">left</div> <div class="right">right</div></body></html>
雙飛翼布局的最大優點是它的相容性——可以相容到IE6.
最後我還想說說CSS3的flex布局方法
該方式的思想是設定一個彈性容器包裹三個元素,並將這個容器設定為水平排列(flex-flow:row),左右兩邊元素設定固定寬度,中間元素設定為flex:1;
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style>.flex { display: flex; flex-flow: row;}.left{ width: 200px; height: 50px; background-color: red;}.center{ flex: 1; height: 50px; background-color: #fff9ca;}.right { width: 300px; height: 50px; background-color: yellow;} </style></head><body><div class="flex"> <div class="left">左邊</div> <div class="center">中間</div> <div class="right">右邊</div></div></body></html>
但不得不說的是flex布局的相容性還不夠完善,所以個人不推薦使用這種方式布局。
嘿嘿,以上就是我能想到的實現左右固定,中間自適應的三列布局的幾種方式啦啦啦