23

我创建了一个带有前置伪元素的“标题”元素。伪元素必须在父元素之后。在我给我的“标题”一个 z-index 之前,一切都很好。

我想要的是:前景中的黄色“标题”,背景中的红色伪元素和黄色“标题”元素上的简单 z-index 30。

header { 
    background: yellow;
    position:relative;
    height: 100px;
    width: 100px;
    z-index:30; /*This is the problem*/
}

header::before { 
    content:"Hide you behind!";
    background: red;
    position:absolute;
    height: 100px;
    width: 100px;
    top:25px;
    left:25px;
    z-index:-1;
}

您可以在此链接 ( http://jsfiddle.net/tZKDy/ ) 上测试我的问题,并且在设置/删除 de 'header' 元素上的 z-index 时会看到问题。

4

2 回答 2

33

::before 伪元素放置在标题元素内。

CSS规范

:before 和 :after 伪元素与其他框交互,就好像它们是插入到相关元素中的真实元素一样。

为 header 元素设置 z-index会创建一个新的 Stacking Context,因此您创建的新伪元素不能浮动在 header 元素后面,因为它必须超出该 Stacking Context。

我建议您只需在 header 元素之前加上另一个元素,因此默认情况下它会正确堆叠。例子

于 2011-10-19T14:31:39.700 回答
1

我使用了 z-index:-1 (在此处输入链接描述

a {
    position: relative;
    z-index: 1;
    text-align: center;
    display: table-cell;
    vertical-align: middle;

    &::before {
        content: "";
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: $secondryColor;
        z-index: -1;
    }   
}
于 2020-03-10T11:40:23.637 回答