gpt4 book ai didi

css - 在元素下使用::after时的z-index

转载 作者:技术小花猫 更新时间:2023-10-29 10:18:42 24 4
gpt4 key购买 nike

如果我们将 z-indexposition: absolute; 结合使用,则可以将元素的 ::before 置于其自身之下。 another question 上有一个很好的例子(jsfiddle.net/Ldtfpvxy)。

基本上

<div id="element"></div>

#element {
position: relative;
width: 100px;
height: 100px;
background-color: blue;
}

#element::after {
content: "";
width: 150px;
height: 150px;
background-color: red;

/* create a new stacking context */
position: absolute;
z-index: -1; /* to be below the parent element */
}

呈现:

enter image description here

因此堆叠上下文/顺序由 z-index 定义。但是当我将 z-index: 1; 应用于元素并将 z-index: -1; 应用于其 ::before 我无法实现一样的东西。

仅当我从元素中省略 z-index 时。

知道这是为什么吗?元素是否在其 ::before::after 伪元素之后呈现,以便它们获得相同的 z-index

工作: https://jsfiddle.net/Ldtfpvxy/
不工作: https://jsfiddle.net/Ldtfpvxy/1/ (只添加 z-index: 1; 到元素)

最佳答案

您的 div 及其::after 伪元素是同一堆叠上下文的成员,在本例中为根堆叠上下文。您为伪元素提供的新堆叠上下文将用作对其子元素(不存在)的引用,但 z-index 值适用于当前堆叠上下文。和 CSS spec为每个堆叠上下文指定以下绘制顺序:

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

看,具有负堆栈级别的子堆栈上下文,例如您的 div::after具有堆栈级别 0 的定位后代之前绘制>,例如 div 本身。这解释了您注意到的行为。

关于css - 在元素下使用::after时的z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com