做過 CSS 布局的人都明白,真正需要反覆琢磨的其實就兩件事:float 和 position。把這兩個屬性的取值與適用場景吃透,再配合幾個常見結構模板,大部分頁面都能穩穩落地。
語法為 float: none | left | right。
none:預設值,元素不浮動。left:元素浮到左側,其後的文本流向它的右邊。right:元素浮到右側,其後的文本流向它的左邊。/* 注意:清除浮動本身是違背 web 標準意圖的寫法,這裡只是為了說明它下方的元素需要 clear */
#wrap{width:100%; height:auto;}
#column1{float:left; width:40%;}
#column2{float:right; width:60%;}
.clear{clear:both;}
語法為 position: static | absolute | fixed | relative。
static:預設值,不特別定位,完全遵循文件正常的排版規則。absolute:把元素從文件流中抽離,用 left/right/top/bottom 相對於「最近的、已設定定位的父元素」做絕對定位;若找不到這樣的父元素,則以 body 為基準。層疊關係由 z-index 決定。fixed:定位方式同樣是絕對定位,但坐標以視窗為參照,滾動時位置固定不動。relative:元素仍留在文件流中佔位,只是依 left/right/top/bottom 在原本位置上做偏移。#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。
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{margin-left:auto; margin-right:auto; width:400px;}
#content-end{margin-left:auto; margin-right:auto; width:400px;}
body{margin:0; padding:0; text-align:center;}
#content-top{margin-left:auto; margin-right:auto; width:400px;}
#content-mid{margin-left:auto; margin-right:auto; width:400px;}
#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{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:420px;}
#header{width:700px; margin-right:auto; margin-left:auto;}
#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 0 190px;}
#right{position:absolute; top:0; right:0; width:120px;}
<div id="wrap">
<div id="column1">這裡是第一列</div>
<div id="column2">這裡是第二列</div>
<!-- 標準不建議這樣用,但要知道它下方的元素必須清除浮動 -->
<div id="column3">這裡是第三列</div>
</div>
#wrap{width:100%; height:auto;}
#column1{float:left; width:30%;}
#column2{float:left; width:30%;}
#column3{float:right; width:40%;}
.clear{clear:both;}
body{
margin:0;
padding-left:200px; /* LC full width */
padding-right:190px; /* RC full width + CC padding */
min-width:200px;
}
.column{position:relative; float:left;}
#center{width:100%;}
#left{
width:200px; /* LC width */
right:200px; /* LC full width */
margin-left:-100%;
}
#right{
width:190px; /* RC width */
margin-right:-100%;
}
浮動元素一定要記得清除,否則父容器高度會塌陷;寬度建議用百分比搭配 min-width 保底,避免視窗過窄時三列擠成一團。負 margin 那套寫法雖然效果漂亮,但可讀性差,維護時最好把註解寫清楚每一行的用途。