DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS特效代碼
z-index 堆疊層級關係完整解析
編輯:CSS特效代碼     

z-index 是控制元素前後覆蓋關係的關鍵屬性。理解它的運作方式,才能避免版面中的元素「該在上面卻被壓住」的困擾。

定義與用法

z-index 屬性用來設定元素的堆疊順序。擁有較高堆疊順序的元素,總是會顯示在堆疊順序較低的元素前方。

  • 元素可以擁有負的 z-index 值。
  • z-index 只對「定位元素」有效,也就是必須先設定 position: absolute(或 relative、fixed 等)才能生效。

這個屬性決定了定位元素沿著 z 軸(垂直於顯示區、指向使用者)的位置:數值為正表示離使用者更近,為負則表示離使用者更遠。

相同 z-index 值的優先關係

當兩個元素設定相同的 z-index 值時,在 HTML 中位置較後的元素,其層級會高於位置較前的元素。例如:

<style type="text/css">
.first { width: 200px; height: 500px; position: absolute; background: #00f; z-index: 100; }
.second{ width: 250px; height: 250px; position: absolute; background: #f33; z-index: 100; }
</style>

<body>
<div class="first">first</div>
<div class="second">second</div>
</body>

由於 .second 寫在 .first 之後,因此 class 為 second 的 div 會疊在 first 的上方。

關鍵陷阱:z-index 只比較兄弟元素

z-index 只用來區分「同一層級兄弟元素」的高低,並不是拿來比較整頁所有元素的高度。以下例子說明了這一點:

<style type="text/css">
.first      { width: 200px; height: 500px; position: absolute; top: 0;   background: #00f; z-index: 80; }
.second     { width: 250px; height: 250px; position: absolute; top: 50px; background: #f33; z-index: 100; }
.first-child{ width: 250px; height: 250px; position: absolute; top: 0;   background: #333; z-index: 101; }
</style>

<body>
<div class="first">first
  <div class="first-child">first-child</div>
</div>
<div class="second">second</div>
</body>

雖然 .first-child 的 z-index(101)大於 .second 的 z-index(100),但畫面上 first-child 卻仍顯示在 second 的下方。這是因為 first-child 是 first 的子元素,它的層級優先被父元素 first(z-index 80)所限制,無法超越與 first 同層的 second。

重點整理

要正確使用 z-index,務必記得兩件事:一是元素必須先具備定位屬性,二是層級比較只在相同的父元素之下進行。理解「堆疊上下文」的概念,才能精準掌控複雜版面的層層覆蓋關係。

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