DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
DIV style 常用屬性(二):padding、position 與 z-index
編輯:CSS詳解     

這一組是版面控制的骨幹:內距、定位與層疊順序。

padding:內距

<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;

position:定位方式

<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。

z-index:層疊順序

<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 設了沒作用」問題的答案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved