聖杯布局和雙飛翼布局解決的問題是一樣的,就是兩邊頂寬,中間自適應的三欄布局,中間欄要在放在文檔流前面以優先渲染。
聖杯布局和雙飛翼布局解決問題的方案在前一半是相同的,也就是三欄全部float浮動,但左右兩欄加上負margin讓其跟中間欄div並排,以形成三欄布局。
不同在於解決”中間欄div內容不被遮擋“問題的思路不一樣:
聖杯布局,為了中間div內容不被遮擋,將中間div設置了左右padding-left和padding-right后,將左右兩個div用相對布局position: relative並分別配合right和left屬性,以便左右兩欄div移動后不遮擋中間div。
雙飛翼布局,為了中間div內容不被遮擋,直接在中間div內部創建子div用於放置內容,在該子div里用margin-left和margin-right為左右兩欄div留出位置。
多了1個div,少用大致4個css屬性(聖杯布局中間divpadding-left和padding-right這2個屬性,加上左右兩個div用相對布局position: relative及對應的right和left共4個屬性,一共6個;而雙飛翼布局子div里用margin-left和margin-right共2個屬性,6-2=4),個人感覺比聖杯布局思路更直接和簡潔一點。
簡單說起來就是”雙飛翼布局比聖杯布局多創建了一個div,但不用相對布局了“,而不是你題目中說的”去掉relative"就是雙飛翼布局“。
最終界面是一樣的:
對比圖:
下面直接上代碼:
聖杯布局:
<body> <div id="hd">header</div> <div id="bd"> <div id="middle">middle</div> <div id="left">left</div> <div id="right">right</div> </div> <div id="footer">footer</div> </body> <style> #hd{ height:50px; background: #666; text-align: center; } #bd{ /*左右欄通過添加負的margin放到正確的位置了,此段代碼是為了擺正中間欄的位置*/ padding:0 200px 0 180px; height:100px; } #middle{ float:left; width:100%;/*左欄上去到第一行*/ height:100px; background:blue; } #left{ float:left; width:180px; height:100px; margin-left:-100%; background:#0c9; /*中間欄的位置擺正之后,左欄的位置也相應右移,通過相對定位的left恢復到正確位置*/ position:relative; left:-180px; } #right{ float:left; width:200px; height:100px; margin-left:-200px; background:#0c9; /*中間欄的位置擺正之后,右欄的位置也相應左移,通過相對定位的right恢復到正確位置*/ position:relative; right:-200px; } #footer{ height:50px; background: #666; text-align: center; } </style>
雙飛翼布局:
<body> <div id="hd">header</div> <div id="middle"> <div id="inside">middle</div> </div> <div id="left">left</div> <div id="right">right</div> <div id="footer">footer</div> </body> <style> #hd{ height:50px; background: #666; text-align: center; } #middle{ float:left; width:100%;/*左欄上去到第一行*/ height:100px; background:blue; } #left{ float:left; width:180px; height:100px; margin-left:-100%; background:#0c9; } #right{ float:left; width:200px; height:100px; margin-left:-200px; background:#0c9; } /*給內部div添加margin,把內容放到中間欄,其實整個背景還是100%*/ #inside{ margin:0 200px 0 180px; height:100px; } #footer{ clear:both; /*記得清楚浮動*/ height:50px; background: #666; text-align: center; } </style>
<body> <style type="text/css"> body{margin:0; padding:0;} .boxA{width:180px;background: #CD0000 } .boxB{width:600px;background: #9ACD32} .boxC{width:180px;background: #87CEFF} .box{ height: 300px; float: left;} /*ABC*/ /*.boxA{position: relative;left:-960px;} .boxB{margin-left:180px;}*/ /*CBA*/ .container{ padding: 0 180px;} .boxB{width: 100%; text-align: right;} .boxC{position: relative;margin-left: -180px;left:-100%;} .boxA{position: relative;margin-left: -180px;right:-180px;} /*BAC*/ /*.boxC{float:right;} .container{width: 960px;}*/ </style> <p>現有並列的三列布局結構,從左至右依次為 A, B, C, 寬度分別為180px, 600px, 180px。要求在不改變 Html 結構的情況下用CSS實現:ABC,CBA,BAC 三種布局及在CBA排列下使B寬度自適應(三列總寬度100%),不能使用針對瀏覽器的CSS Hack.</p> <div class="container"> <div class="box boxB">B</div> <div class="box boxC">C</div> <div class="box boxA">A</div> </div> </body>