掌握 float 與 position 這兩大布局利器,你就能應付絕大多數的頁面排版需求。本文從屬性取值講起,並附上常見的單欄、多欄布局範例。
none:預設值,不浮動。left:元素向左浮動,文本流向右邊。right:元素向右浮動,文本流向左邊。static:預設值,遵循 HTML 定位規則。absolute:脫離文檔流,相對最近的已定位父元素做絕對定位。fixed:以絕對方式定位,但相對於視窗固定。relative:不脫離文檔流,依 top、left 等屬性在原位置上偏移。float 是相對靈活的,會隨瀏覽器大小與解析度變化而重新排列;position(尤其 absolute)則較為固定。因此一般情況下,響應式或彈性版面仍以 float 布局為主。
單行兩列:
#wrap{ width:100%; }
#column1{ float:left; width:40%; }
#column2{ float:right; width:60%; }
.clear{ clear:both; }
元素居中(單行一列):
body{ margin:0; padding:0; text-align:center; }
#content{ margin-left:auto; margin-right:auto; width:400px; }
三行兩列(含頁首與頁腳):
#header{ width:700px; margin:auto; }
#bodycenter{ width:700px; margin:auto; }
#bodycenter #dv1{ float:left; width:280px; }
#bodycenter #dv2{ float:right; width:420px; }
#footer{ width:700px; margin:auto; clear:both; }
掌握了這些基礎組合,你就能自由拼出各種版面結構。