下邊將介紹前端很流行的佈局方式,要求兩邊固定,中間自適應。比較流行的佈局方式有聖盃佈局,雙翼佈局,flex佈局、絕對定位佈局。css
聖盃佈局,顧名思義,他具備如下特色:html
1.三列布局,中間自適應,兩邊定寬;前端
2.中間欄要求在瀏覽器中優先展現;瀏覽器
接下來咱們看實現方式:佈局
div咱們這樣寫:flex
<div class="container"> <div class="main">main</div> <div class="left">left</div> <div class="right">right</div> </div>
下邊直接看代碼實現:spa
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> <style type="text/css"> .container { padding: 0 300px 0 200px; } .left, .main, .right { position: relative; min-height: 130px; float: left; } .left { left: -200px; margin-left: -100%; background: green; width: 200px; } .right { right: -300px; margin-left: -300px; background-color: red; width: 300px; } .main { background-color: blue; width: 100%; } </style> </head> <body> <div class="container"> <div class="main">main</div> <div class="left">left</div> <div class="right">right</div> </div> </body> </html>
出來的樣子就是這樣:code
代碼中main的寬度設爲100%,left跟right恰好固定到了左右兩邊。其中使用了一個margin-left爲負的值,負的margin-left會讓元素沿文檔流向左移動,若是負的數值比較大就會一直移動到上一行。設置left部分的margin-left爲-100%,就會使left向左移動一整個行的寬度,因爲left左邊是父元素的邊框,因此left繼續跳到上一行左移,一直移動到上一行的開頭,並覆蓋了main部分(仔細觀察下圖,你會發現main裏面的字「main」不見了,由於被left遮住了),left上移事後,right就會處於上一行的開頭位置,這時再設置right部分margin-left爲負的寬度,right就會左移到上一行的末尾。 接下來只要把left和right分別移動到這兩個留白就能夠了。可使用相對定位移動 left和right部分。htm
聖盃佈局和雙飛翼佈局解決問題的方案在前一半是相同的,也就是三欄所有float浮動,但左右兩欄加上負margin讓其跟中間欄div並排,以造成三欄佈局。不一樣在於解決 「中間欄div內容不被遮擋」問題的思路不同。 代碼實現:blog
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>index</title> <style type="text/css"> .left, .main, .right { float: left; min-height: 130px; text-align: center; } .left { margin-left: -100%; background: green; width: 200px; } .right { margin-left: -300px; background-color: red; width: 300px; } .main { background-color: blue; width: 100%; } .content{ margin: 0 300px 0 200px; } </style> </head> <body> <div class="container"> <div class="main"> <div class="content">main</div> </div> <div class="left">left</div> <div class="right">right</div> </div> </body> </html>
雙飛翼佈局比聖盃佈局多使用了1個div,少用大體4個css屬性(聖盃佈局container的 padding-left和padding-right這2個屬性,加上左右兩個div用相對佈局position: relative及對應的right和left共4個屬性,;而雙飛翼佈局子div裏用margin-left和margin-right共2個屬性,比聖盃佈局思路更直接和簡潔一點。簡單提及來就是:雙飛翼佈局比聖盃佈局多建立了一個div,但不用相對佈局了。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>實現三欄水平佈局之Flex佈局</title> <style type="text/css"> .container{ display: flex; min-height: 130px; } .main{ flex-grow: 1; background-color: blue; } .left{ order: -1; flex-basis: 200px; background-color: green; } .right{ flex-basis: 300px; background-color: red; } </style> </head> <body> <div class="container"> <div class="main">main</div> <div class="left">left</div> <div class="right">right</div> </div> </body> </html>
絕對定位佈局就是至關於把左右兩個div絕對定位到左右兩邊的padding就能夠了,這裏就不寫代碼了。
本文參考CSDN 做者 萌主_iii 。