描述 z-index 以及如何在 CSS 中形成堆叠上下文
堆叠顺序描述了 HTML 元素的放置顺序。默认情况下,HTML 元素按以下顺序定位:
- 根元素()
- 按定义顺序排列的非定位元素(没有描述位置的元素,即静态元素)
- 按定义顺序定位元素(位置不是静态的元素)
让我们尝试了解默认堆叠顺序是如何工作的:
示例 1:默认堆叠顺序
下面是理解默认堆叠顺序的 HTML 和 CSS 代码:
HTML
Default stacking order
Positioned
Positioned
Non-positioned
Output:Output for above code snippetExplanation: From the output, we can see that although we defined the red box in the end, it still came on top of the green and blue box because it was non-positioned whereas the other two boxes were positioned.z-index: In order to change the stacking order, we can use z-index. Element with higher z-index is placed on top of the element with lower z-index. Let us use the same. An important thing to note is that in order to use z-index, elements should be positioned. To learn more about CSS, positions, refer this article.Example 2: Stacking with z-indexWe use the previous example, but this time we will apply a z-index value to the green and blue boxes.
HTML
Stacking with z-index
Positioned
Positioned
Non-positioned
Output:Output with z-indexExplanation: We observe that green box is placed on top of blue box because green box has a higher z-index value(3) than blue box(2). Also, note that red box has a z-index value of 100, but there is no effect since it is a non-positioned element.Example 3: Now in order to understand stacking context, Let’s say we add another box to the layout and we want the blue box to be behind it.
HTML
Stacking context
Positioned
Positioned
Positioned
Positioned
Non-positioned
Output:Stacking contextExplanation: We have added two new boxes: orange and purple. As expected, green box is on top of purple box because green box has higher z-index value than purple box. However, the orange box is still behind the blue box despite having a higher z-index value. Why is that so? By applying z-index value to an element, a stacking context is formed. The fact that a stacking context is formed means it also affects its child elements(orange box is a child of green box in this case). We can change the stacking order of child elements, but it will only have a meaning in that stacking context.So, the orange box is still behind blue box because they are not in the stacking context anymore.Example 4: If we want to place blue box on top of orange box, there are two things that we can do:Either make the blue box a child element of green boxDefine orange box outside the green boxHere, we will make blue box a child element of green box.
HTML
Modified stacking context
Positioned
Positioned
Positioned
Positioned
Non-positioned
Output:Explanation: In above example, we see that blue box is behind orange box because they are in the same stacking context. There are other properties that also cause a new stacking context to be formed. Some examples are: transform, filter etc.
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。