::之前的伪元素,负z-index不显示在父元素后面

时间:2013-11-09 22:43:27

标签: html css

我发誓我已经完成了这一百次,但是对于我的生活,我无法弄清楚为什么我的:before伪元素的背景显示在文本后面但不在锚点的背景后面。想法?

.button {
    background: tomato;
    padding: 10px 30px;
    margin: 20px 0;
    display: inline-block;
}

.button:hover {
    margin: 18px 0 22px 2px;
    position: relative;
    z-index: 2;
}

.button:hover:after {
    position: absolute;
    background: red;
    top:-2px;
    left: -2px;
    content: "";
    z-index: -10;
    width: 100%;
    height: 100%;
}
<a class="button" href="#">Meow</a>

此处示例:http://jsfiddle.net/cfree/hnKLr/

2 个答案:

答案 0 :(得分:11)

向元素添加z-index值时,将创建新的堆叠上下文。该元素的每个孩子都会叠加在它上面。

因此,当您想要在其父元素后面放置元素时,只需在父元素上创建堆叠上下文。您仍然需要使用负z索引,因为父级的默认堆栈级别为0(无论元素是什么上下文)

答案 1 :(得分:2)

::before::after伪元素的命名有点令人困惑 - 它们的行为就好像它们是匹配元素的子元素,而不是它的兄弟元素。

在这种特殊情况下,似乎box-shadow最合适:

.button:hover {
    box-shadow: -2px -2px 0 red;
}

Is this the effect you were looking for?