经典的三栏布局:圣杯布局,双飞翼布局,flex布局
需求:
兩邊欄固定寬度,中間寬度自適應,一般左邊欄為導航,右邊欄為廣告,中間欄為主要內容的展示,div塊上中間欄放在第一位,重要的東西放在文檔流前面可以優先渲染。
圣杯布局和雙飛翼布局的共同特點都是利用float+margin的負值來實現并列的結構。首先中間欄width 100%后,左右欄被擠在第二行,左欄margin-left設置為-100%后(實際即為中間欄的寬度),這樣左欄就跟中間欄并列,且左欄和中間欄的左邊緣對其,同理右欄margin-left(因為float是向左的)設置為右欄自己寬度的負值,這樣就升上去,且右邊緣和中間欄的右邊欄重合。
現在的問題就是左右欄占用了main的空間。圣杯布局和雙飛翼的布局的處理差異也就在這里:
1.圣杯布局
圣杯布局的處理方式為父容器container設置padding-left和padding-right為左右欄的寬度,此時左右欄會表現往里面縮一些,因為padding只是調節內部元素的位置并不會顯示width的content(盒子模型),對外部元素沒影響。此時就需要用相對定位調節左右欄left和right為父容器pading左右值的負值,這樣就移開了左右欄對中間欄的占據,且中間欄的內容全部顯示在width的content中。
代碼:
<!-- 圣杯布局 --> <!DOCTYPE html> <html><head><style>.left {background: #E79F6D;width: 150px;float: left;}.main {background: #D6D6D6;width: 100%;float: left;}.right {background: #77BBDD;width: 190px;float: left;}.left {margin-left: -100%;}.right{margin-left:-190px;}/* 設置padding后,margin是不占用其他元素的padding的,padding只是用來調節內部元素與本身的距離,margin調節才是本身與周圍之間的距離 */.con {padding-left: 150px;padding-right: 190px;}.left {position: relative;left: -150px;}.right {position: relative;right: -190px;}</style> </head><body><div class="con"><div class="main">Main</div><div class="left">Left</div><div class="right">Right</div></div> </body></html>2. 雙飛翼布局
雙飛翼并列的方式與圣杯布局相同,但是擯棄了相對定位的方式。而是給中間欄加了一個父容器,父容器設置float,子容器設置margin-left和margin-right抵消左右欄布局的寬度,避免content顯示部分被左右欄覆蓋到自己寬度。(注意不是float左右因為margin移動了,而是是中間欄的content的內容width一部分寬度分給了margin,自己縮小了,float是脫離的文檔流的,無視block,但是受影響到文字,參考文字環繞)。
代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.main-wrapper {float: left;width: 100%;}.main {height: 300px;/* 多10px間距 */margin-left: 210px;margin-right: 190px;background-color: rgba(255, 0, 0, .5);}.sub {float: left;width: 200px;height: 300px;margin-left: -100%;background-color: rgba(0, 255, 0, .5);}.extra {float: left;width: 180px;height: 300px;margin-left: -180px;background-color: rgba(0, 0, 255, .5);}</style> </head> <body><div class="main-wrapper"><div class="main"></div></div><div class="sub"></div><div class="extra"></div></body> </html>先進而簡單的flex布局
1.order指定順序,默認為0,越小越靠前
2.flex-grow屬性定義項目的放大比例,默認為0,即如果存在剩余空間,也不放大
3.flex-basic:屬性定義了在分配多余空間之前,項目占據的主軸空間(main size)。瀏覽器根據這個屬性,計算主軸是否有多余空間。它的默認值為auto,即項目的本來大小。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><style>.container {display: flex;min-height: 300px;}.left {order: -1;flex-basis: 300px;background-color: green;}.right {flex-basis: 150px;background-color: red;}.main {flex-grow: 1;background-color: blue;}</style><title>Document</title> </head> <body><div class="container"><div class="main"></div><div class="left"></div><div class="right"></div></div></body> </html>轉載于:https://www.cnblogs.com/zhangmingzhao/p/9332174.html
總結
以上是生活随笔為你收集整理的经典的三栏布局:圣杯布局,双飞翼布局,flex布局的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 模拟人生4绅士包怎么用 MuMu模拟器官
- 下一篇: Get Set的问题解决