CSS Z-index 与 before 伪元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7822078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Z-index with before pseudo-element
提问by Tom Claus
I've created a 'header' element with a before-pseudo element. the pseudeo element must be behind the parent element. Everything works great till the moment I give my 'header' a z-index.
我创建了一个带有前伪元素的“标题”元素。伪元素必须在父元素之后。一切都很好,直到我给我的“标题”一个 z-index。
What I want: The yellow 'header' on the foreground, the red pseudo-element in the background and a simple z-index of 30 on the yellow 'header' element.
我想要的是:前景上的黄色“标题”,背景中的红色伪元素以及黄色“标题”元素上的简单 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;
}
You can test my problem on this link (http://jsfiddle.net/tZKDy/) and you see the problem when you set/remove the z-index on de 'header' element.
您可以在此链接 ( http://jsfiddle.net/tZKDy/)上测试我的问题,并且在设置/删除 de 'header' 元素上的 z-index 时会看到问题。
回答by RC-1290'Dreadnought'
The ::before pseudo-element is placed inside the header element.
::before 伪元素放置在标题元素内。
The :before and :after pseudo-elements interact with other boxes as if they were real elements inserted just inside their associated element.
:before 和 :after 伪元素与其他框交互,就好像它们是插入到关联元素中的真实元素一样。
Setting the z-index for the header element creates a new Stacking Context, so the new pseudo element you created can not float behind the header element, because it would have to go outside that Stacking Context.
为 header 元素设置 z-index会创建一个新的 Stacking Context,因此您创建的新伪元素不能浮动在 header 元素后面,因为它必须在该 Stacking Context 之外。
I suggest that you simply precede the header element by another element, so it stacks correctly by default. Example.
我建议您只需在标题元素之前添加另一个元素,这样默认情况下它就会正确堆叠。例子。
回答by Velihan Kara
I used z-index:-1 (enter link description here)
我使用了 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;
}
}