絕大多數網站的骨架,都能歸類成「幾行幾欄」的組合。把這些基礎範式收集起來,之後要搭版面時直接取用即可。
以下範例刻意不寫 margin、padding、border,只保留決定結構的部分,方便你往上加自己的樣式。
body { margin: 0; padding: 0; text-align: center; }
#content {
margin-left: auto;
margin-right: auto;
width: 370px;
}
把同一組宣告套用到多個區塊即可:
#content-top,
#content-mid,
#content-end {
margin-left: auto;
margin-right: auto;
width: 370px;
}
三行一列就是 header、內容、footer 的直式堆疊,最傳統的部落格或企業站首頁。
#bodycenter { width: 700px; margin-right: auto; margin-left: auto; overflow: auto; }
#bodycenter #dv1 { float: left; width: 280px; }
#bodycenter #dv2 { float: right; width: 410px; }
外層的 overflow:auto 同時負責收浮動,避免父容器塌陷。左右寬度相加小於 700px,留出的餘裕就是欄間距。
#header {
width: 700px;
margin-right: auto;
margin-left: auto;
overflow: auto;
}
#bodycenter { width: 700px; margin-right: auto; margin-left: auto; overflow: auto; }
#bodycenter #dv1 { float: left; width: 280px; }
#bodycenter #dv2 { float: right; width: 410px; }
三行兩列再加上一個同寬的 #footer 即可,這是最常見的「上方頁首、中間兩欄、下方頁尾」結構。
#left { position: absolute; top: 0; left: 0; width: 120px; }
#middle { margin: 20px 190px 20px 190px; }
#right { position: absolute; top: 0; right: 0; width: 120px; }
左右兩欄各自釘在視窗兩側,中間欄用左右 margin 讓位。這種做法的優點是 HTML 順序可以是「中間優先」,有利於 SEO 與延遲載入;缺點是兩側欄高度必須事先掌握。
<div id="wrap">
<div id="column">
<div id="column1">第一列</div>
<div id="column2">第二列</div>
<div class="clear"></div>
</div>
<div id="column3">第三列</div>
<div class="clear"></div>
</div>
#wrap { width: 100%; height: auto; }
#column { float: left; width: 60%; }
#column1 { float: left; width: 30%; }
#column2 { float: right; width: 30%; }
#column3 { float: right; width: 40%; }
.clear { clear: both; }
先把右側獨立欄浮動到最右,再把剩下空間切成兩欄。這種巢狀結構比三欄並排更能承受欄高不齊的情況。
<div id="center" class="column"><h1>主要內容</h1></div> <div id="left" class="column"><h2>左側欄</h2></div> <div id="right" class="column"><h2>右側欄</h2></div>
body {
margin: 0;
padding-left: 200px;
padding-right: 190px;
min-width: 240px;
}
.column { position: relative; float: left; }
#center { width: 100%; }
#left { width: 180px; right: 240px; margin-left: -100%; }
#right { width: 130px; margin-right: -100%; }
這是天生的「中欄優先」三欄佈局:中間欄先出現在 HTML 並佔滿寬度,左右欄靠負 margin 拉回可視範圍。經典的 One True Layout 就屬於這一派。
在單行三列的外頭加上 #header 與 #footer,各自 width:100% 即可:
#header, #footer { width: 100%; height: auto; }
#wrap { width: 100%; height: auto; }
#column { float: left; width: 60%; }
#column1 { float: left; width: 30%; }
#column2 { float: right; width: 30%; }
#column3 { float: right; width: 40%; }
.clear { clear: both; }
這就是絕大多數企業網站與入口網站的骨架。
這些是結構骨架,不是最終樣式。真正上線時你還需要處理間距、斷點、圖片自適應與舊瀏覽器相容。若不必支援 IE,上面那些浮動與負 margin 的技巧可以用 grid 一行取代——例如三欄等高的寫法是 display:grid; grid-template-columns: 200px 1fr 190px;,中欄優先的排序問題也不再存在。理解這些舊寫法的用意,比記住語法更重要。