摘要:[CSS]Z-index學習紀錄
z-index是CSS定義中的一個屬性,用來做出推疊呈現的概念,當我們把網頁上呈現的每一個物件都一個個放在同區域且互相分出層次的推放時(好比一張張推在那邊的廣告DM)總會有N張呈現在最上面(最容易被看到)跟最下面(最不容易被看到)
簡單來講,我們可以透過z-index這個屬性來控制推在一起HTML標籤呈現的順序。
以下是一個簡單的範例呈現推在一起的效果
Check out this Pen!
Check out this Pen!
Here's the challenge: try to see if you can make the red <span>
element stack behind the blue and green <span>
elements without breaking any of the following rules:
- Do not alter the HTML markup in any way.
- Do not add/change the z-index property of any element.
- Do not add/change the position property of any element.
有興趣的可以動手挑戰一下後到上面的原網址去看一下答案瞜~~!!
(這邊分遠一點,避免洩漏答案)
這裡很特別的是透過opacity竟然也達到了呈現順序的修改
div:first-child { opacity: .99; }
上面這一行很簡單的指定了第一個div tag的opacity低於其他兩個(預設為1)
導致她呈現上被移到最後一層,這邊解說就麻煩回原網址看了,節錄重點如下
Stacking Order Within the Same Stacking Context
Here are the basic rules to determine stacking order within a single stacking context (from back to front):
- The stacking context's root element
- Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
- Non-positioned elements (ordered by appearance in the HTML)
-
Positioned elements (and their children) with a z-index value of
auto
(ordered by appearance in the HTML) - Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
Note: positioned elements with negative z-indexes are ordered first within a stacking context, which means they appear behind all other elements. Because of this, it becomes possible for an element to appear behind its own parent, which is normally not possible. This will only work if the element's parent is in the same stacking context and is not the root element of that stacking context. A great example of this is Nicolas Gallagher's CSS drop-shadows without images.
Global Stacking Order
With a firm understanding of how/when new stacking contexts are formed as well as a grasp of the stacking order within a stacking context, figuring out where a particular element will appear in the global stacking order isn't so bad.
The key to avoid getting tripped up is being able to spot when new stacking contexts are formed. If you're setting a z-index of a billion on an element and it's not moving forward in the stacking order, take a look up its ancestor tree and see if any of its parents form stacking contexts. If they do, your z-index of a billion isn't going to do you any good.
如果對於z-index預設值有興趣的可以把它alert出來看看搂(上面第一個範例js註解取消即可看到)