float
實現基於純
float
實現的三欄佈局須要將中間的內容放在HTML結構的最後,不然右側會沉在中間內容的下側css原理:元素浮動後,脫離文檔流,後面的元素受浮動影響,設置受影響元素的
margin
值便可html
兩邊固定寬度,中間寬度自適應。佈局
利用中間元素的margin
值控制兩邊的間距flex
寬度小於左右部分寬度之和時,右側部分會被擠下去flexbox
<div class="wrap"> <div class="left">左側</div> <div class="right">右側</div> <div class="middle">中間</div> </div> <style type="text/css"> .wrap {background: #eee; overflow: hidden; padding: 20px;} <!-- 生成BFC,計算高度時考慮浮動的元素 --> .left {width: 200px; height: 50px; float: left; background: coral;} .right {width: 120px; height: 200px; float: right; background: lightblue;} .middle {margin-left: 220px; background: lightpink; margin-right: 140px;} </style>
position
實現基於絕對定位的三欄佈局:注意絕對定位的元素脫離文檔流,相對於最近的已經定位的祖先元素進行定位。無需考慮HTML中結構的順序spa
缺點:有頂部對齊問題,須要進行調整,注意中間的高度爲整個內容的高度3d
<div class="wrap"> <div class="left">左側</div> <div class="middle">中間</div> <div class="right">右側</div> </div> <style type="text/css"> .wrap {background: lightpink;} .left {width: 200px; height: 100px; position: absolute; top: 0; left: 0; background: coral;} .right {width: 120px; height: 100px; position: absolute; top:0; right: 0; background: lightblue;} .middle {height: 50px; margin: 0 140px 0 220px; background: #555;} </style>
float
和BFC
配合聖盃佈局必須將中間部分的HTML結構寫在最前面,三個元素均設置向左浮動。兩側元素寬度固定,中間設置爲100%;而後利用左側元素負的
margin
值進行偏移,覆蓋在中間的寬度之上;右側的元素一樣利用負的margin
值進行覆蓋code
存在的問題:不能自適應高度htm
<div class="wrap"> <div class="middle"> <div class="main">中間</div> </div> <div class="left">左側</div> <div class="right">右側</div> </div> <style type="text/css"> .wrap {overflow: hidden;} .left {float: left; width: 200px; height: 100px; background: coral; margin-left: -100%;} .middle {float: left; width: 100%; height: 100px; background: lightblue;} .right {float: left; width: 120px; height: 100px; background: gray; margin-left: -120px;} .main {margin: 0 140px 0 220px; background: lightpink;} </style>
flex
佈局flexbox
佈局最簡潔使用,而且沒有明顯缺陷。blog
僅需將容器設置爲display:flex;
,盒內元素兩端對其,將中間元素設置爲100%
寬度便可填充空白,再利用margin
值設置邊距便可
而且盒內元素的高度撐開容器的高度
<div class="wrap"> <div class="left">左側</div> <div class="middle">中間</div> <div class="right">右側</div> </div> <style type="text/css"> .wrap {display: flex; justify-content: space-between;} .left, .right, .middle {height: 100px;} .left {width: 200px; background: coral;} .right {width: 120px; background: lightblue;} .middle {background: #555; width: 100%; margin: 0 20px;} </style>
純float
的三欄佈局須要將中間的內容放在最後;
絕對定位的三欄佈局:元素對其有點問題
聖盃佈局:容器內不能撐開高度
flex
佈局最好,基本沒有大的缺點。
純