這一組是版面控制的骨幹:內距、定位與層疊順序。
<div style="padding: 5px 10px 20px 30px;
background-color: black; width: 500px; height: 500px;">
<div style="width: 200px; height: 200px; background-color: white;"></div>
</div>
格式與 margin 相同,順序為上右下左。觀察黑色 DIV 與白色 DIV 之間的距離即可理解效果。
關鍵提醒:在標準盒模型下,padding 不包含在 width 與 height 之內。一個 width: 100px 加 padding-left: 50px 的元素,實際佔據 150px。逐邊設定用:
padding-left: 50px;
padding-top: 50px;
padding-right: 10px;
padding-bottom: 10px;
<div style="position: relative; top: 10px; left: 10px;
width: 140px; height: 140px; background-color: white;"></div>
<div style="position: absolute; top: 60px; left: 60px;
background-color: silver; width: 100px; height: 100px;"></div>
<div style="position: fixed; top: 210px; left: 210px;
background-color: navy; width: 100px; height: 100px;"></div>
四個取值的行為:
static 遵循一般 HTML 排版規則,top/left 等設定無效。relative 可用 top、left、right、bottom 做偏移,元素仍佔用原本空間。absolute 脫離文件流,以最近的已定位祖先為參考點做絕對定位。fixed 參考的對象是視窗,捲動時不移動;IE6 不支援。
left、top、right、bottom 都是相對於「文檔層次中最近一個已定位對象」的邊界設定。這句話的重點是最近一個已定位對象——若所有祖先都是 static,absolute 元素會以最初的包含塊(通常是視窗)為參考。想讓 absolute 相對於某個容器定位,就必須先把該容器設為 position: relative。
<div style="position: absolute; top: 50px; left: 50px;
width: 100px; height: 100px; background-color: black;"></div>
<div style="position: absolute; top: 60px; left: 60px;
width: 100px; height: 100px; background-color: blue; z-index: 1;"></div>
<div style="position: absolute; top: 70px; left: 70px;
background-color: silver; width: 100px; height: 100px;"></div>
數值越大越上層。若不設 z-index,藍色 DIV 依 HTML 順序會被最後的 silver 蓋住;加上 z-index: 1 後它就跳到最上層。
必要條件:使用 z-index 時,該元素的 position 不能是 static,否則宣告會被忽略。這個規則是無數「z-index 設了沒作用」問題的答案。