### [CSS]Z-index學習紀錄(與opacity的神奇關係)

• 2488
• 0
• CSS
• 2013-08-20

z-index是CSS定義中的一個屬性，用來做出推疊呈現的概念，當我們把網頁上呈現的每一個物件都一個個放在同區域且互相分出層次的推放時(好比一張張推在那邊的廣告DM)總會有N張呈現在最上面(最容易被看到)跟最下面(最不容易被看到)

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.

(這邊分遠一點，避免洩漏答案)

div:first-child {
opacity: .99;
}

### 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):

1. The stacking context's root element
2. 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)
3. Non-positioned elements (ordered by appearance in the HTML)
4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
5. 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.