本文介紹了CSS經(jīng)典三欄布局方案,分享給大家,也給自己做個(gè)筆記,具體如下:
三欄布局,顧名思義就是兩邊固定,中間自適應(yīng)。三欄布局在開(kāi)發(fā)十分常見(jiàn)
1. float布局
最簡(jiǎn)單的三欄布局就是利用float進(jìn)行布局。首先來(lái)繪制左、右欄:
| <style> .left { float: left; width: 100px; height: 200px; background-color: red; } .right { float: right; width: 100px; height: 200px; background-color: yellow; } </style> <div class="container"> <div class="left"></div> <div class="right"></div> <div class="main"></div> </div> | 
此時(shí)可以得到左右兩欄分布:
 
 
接下來(lái)再來(lái)看中間欄如何處理。我們知道對(duì)于float元素,其會(huì)脫離文檔流,其他盒子也會(huì)無(wú)視這個(gè)元素。(但其他盒子內(nèi)的文本依然會(huì)為這個(gè)元素讓出位置,環(huán)繞在周圍。)所以此時(shí)只需在container容器內(nèi)添加一個(gè)正常的div,其會(huì)無(wú)視left和right,撐滿整個(gè)container,只需再加上margin為left right流出空間即可:
| <style> .left { float: left; width: 100px; height: 200px; background-color: red; } .right { float: right; width: 100px; height: 200px; background-color: yellow; } .main { background-color: green; height: 200px; margin-left: 120px; margin-right: 120px; } .container { border: 1px solid black; } <div class="container"> <div class="left"></div> <div class="right"></div> <div class="main"></div> </div> | 
 
 
優(yōu)勢(shì):簡(jiǎn)單
劣勢(shì):中間部分最后加載,內(nèi)容較多時(shí)影響體驗(yàn)
2. BFC 規(guī)則
BFC(塊格式化上下文)規(guī)則規(guī)定:BFC不會(huì)和浮動(dòng)元素重疊。所以如果將main元素設(shè)定為BFC元素即可:
| <style> .left { float: left; width: 100px; height: 200px; background-color: red; } .right { float: right; width: 100px; height: 200px; background-color: yellow; } .main { background-color: green; height: 200px; overflow: hidden; } <div class="container"> <div class="left"></div> <div class="right"></div> <div class="main"></div> </div> |