做 CSS 佈局,最早需要搞懂的兩件事就是浮動與定位。以下從屬性取值談起,再用程式碼對照兩者的行為差異。
float: none | left | right
none:預設值,元素不浮動。left:元素靠左,文本流向它的右側。right:元素靠右,文本流向它的左側。一行兩列的寫法:
<div id="wrap">
<div id="column1">這裡是第一列</div>
<div id="column2">這裡是第二列</div>
<div class="clear"></div> <!-- 提醒下方元素需要清除浮動 -->
</div>
#wrap { width: 100%; height: auto; }
#column1 { float: left; width: 40%; }
#column2 { float: right; width: 60%; }
.clear { clear: both; }
position: static | absolute | fixed | relative
static:預設值,遵循 HTML 的一般定位規則。absolute:從文檔流中抽離,以 left/right/top/bottom 相對於「最近的已定位祖先」做絕對定位;若無這樣的祖先,則以 body 為基準。層疊順序由 z-index 決定。fixed:定位方式同 absolute,但基準是視窗,捲動時不隨內容移動。relative:仍佔用原本的文檔流位置,只是依 offsets 在視覺上偏移。同樣是一行兩列,改用定位:
<div id="wrap">
<div id="column1"><a href="#">這裡是第一列</a></div>
<div id="column2">這裡是第二列</div>
</div>
#wrap { position: relative; width: 770px; }
#column1 { position: absolute; top: 0; left: 0; width: 300px; }
#column2 { position: absolute; top: 0; right: 0; width: 470px; }
關鍵差異是:float 是相對流動的,會隨視窗尺寸與解析度變化而自然伸縮;position 是絕對的,尺寸一旦寫死就不會變。因此一般頁面佈局仍以 float(或現代的 flex/grid)為主,position 留給需要精確錨定的局部元素。
單行一列
body { margin: 0; padding: 0; text-align: center; }
#content { margin-left: auto; margin-right: auto; width: 400px; }
三行一列
body { margin: 0; padding: 0; text-align: center; }
#content-top, #content-mid, #content-end {
margin-left: auto;
margin-right: auto;
width: 400px;
}
單行兩列
#bodycenter { width: 700px; margin-right: auto; margin-left: auto; overflow: auto; }
#bodycenter #dv1 { float: left; width: 280px; }
#bodycenter #dv2 { float: right; width: 420px; }
三行兩列
#header, #bodycenter { width: 700px; margin-right: auto; margin-left: auto; }
#bodycenter #dv1 { float: left; width: 280px; }
#bodycenter #dv2 { float: right; width: 420px; }
#footer { width: 700px; margin-right: auto; margin-left: auto; overflow: auto; clear: both; }
單行三列(絕對定位版)
#left { position: absolute; top: 0; left: 0; width: 120px; }
#middle { margin: 0 190px; }
#right { position: absolute; top: 0; right: 0; width: 120px; }
float 三列(先包一層再切分)
<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; }
至於中間通欄、左右固定寬側欄的做法,則是透過 body 的左右 padding 預留空間,再讓三欄同時浮動並搭配負 margin 疊回正確位置——這類技巧在下一篇文章的三欄佈局中會有更完整的說明。