Z-index 不适用于 position:fixed 伪元素
Z-index not working with position:fixed pseudo-elements
我对这个话题进行了很多研究,一般来说,这个问题的大部分问题都可以通过指定或更改 position
属性来解决。但是,在处理伪元素时情况就不同了。下面CSS是缩减后的测试用例
#div {
background: #f5f;
height: 80vw;
width: 80vw;
max-height: 50px;
max-width: 50px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#div:before {
content: '';
background: #000;
height: 100vw;
width: 100vw;
max-height: 100px;
max-width: 100px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: -1;
}
HTML
<div id="div">hi!</div>
伪元素属于元素本身。所以 z-index
将在所有伪 "childrens" 中工作,但在父级中不起作用,因为它不在同一个堆栈中。
这就像您想更改 z-index
以将 div 置于另一个 div 之上,但第一个是第二个的父级:
div {position:relative;}
.parent {z-index:10; background:red; padding: 5px;}
.children {z-index:5; background:blue;}
<div class="parent">
I need this more z-index than his children
<div class="children">
I need this less z-index than his parent
</div>
</div>
显然不行。同样的情况。
为避免这种情况,您需要更改 HTML 并使用适当的堆栈将伪元素转换为普通元素。
编辑
你的情况,将固定定位改为相对定位即可解决:
http://jsfiddle.net/Kq2PY/166/
但这是一个特殊情况,因为父元素是固定定位的,并且它在正常流程之外工作(固定元素附加到文档,而不是父元素)。所以能用别的方法做的时候尽量避免做这种东西。
我对这个话题进行了很多研究,一般来说,这个问题的大部分问题都可以通过指定或更改 position
属性来解决。但是,在处理伪元素时情况就不同了。下面CSS是缩减后的测试用例
#div {
background: #f5f;
height: 80vw;
width: 80vw;
max-height: 50px;
max-width: 50px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#div:before {
content: '';
background: #000;
height: 100vw;
width: 100vw;
max-height: 100px;
max-width: 100px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: -1;
}
HTML
<div id="div">hi!</div>
伪元素属于元素本身。所以 z-index
将在所有伪 "childrens" 中工作,但在父级中不起作用,因为它不在同一个堆栈中。
这就像您想更改 z-index
以将 div 置于另一个 div 之上,但第一个是第二个的父级:
div {position:relative;}
.parent {z-index:10; background:red; padding: 5px;}
.children {z-index:5; background:blue;}
<div class="parent">
I need this more z-index than his children
<div class="children">
I need this less z-index than his parent
</div>
</div>
显然不行。同样的情况。
为避免这种情况,您需要更改 HTML 并使用适当的堆栈将伪元素转换为普通元素。
编辑
你的情况,将固定定位改为相对定位即可解决:
http://jsfiddle.net/Kq2PY/166/
但这是一个特殊情况,因为父元素是固定定位的,并且它在正常流程之外工作(固定元素附加到文档,而不是父元素)。所以能用别的方法做的时候尽量避免做这种东西。