猿问

是否可以将伪元素的堆叠顺序设置在其父元素之下?

是否可以将伪元素的堆叠顺序设置在其父元素之下?

我试图用:after伪元素CSS选择器

#element {
    position: relative;
    z-index: 1;}#element::after {
    position:relative;
    z-index: 0;
    content: " ";
    position: absolute;
    width: 100px;
    height: 100px;}

好像::after元素不能低于元素本身。

有办法让伪元素比元素本身低吗?


凤凰求蛊
浏览 971回答 3
3回答

饮歌长啸

伪元素被视为其关联元素的后代。若要将伪元素置于其父元素的下面,必须创建新的堆叠上下文若要更改默认堆叠顺序,请执行以下操作。定位伪元素(绝对值)并分配一个z-索引值而不是“自动”创建新的堆叠上下文。#element&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;relative;&nbsp;&nbsp;/*&nbsp;optional&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;width:&nbsp;100px; &nbsp;&nbsp;&nbsp;&nbsp;height:&nbsp;100px; &nbsp;&nbsp;&nbsp;&nbsp;background-color:&nbsp;blue;}#element::after&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;content:&nbsp;""; &nbsp;&nbsp;&nbsp;&nbsp;width:&nbsp;150px; &nbsp;&nbsp;&nbsp;&nbsp;height:&nbsp;150px; &nbsp;&nbsp;&nbsp;&nbsp;background-color:&nbsp;red; &nbsp;&nbsp;&nbsp;&nbsp;/*&nbsp;create&nbsp;a&nbsp;new&nbsp;stacking&nbsp;context&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute; &nbsp;&nbsp;&nbsp;&nbsp;z-index:&nbsp;-1;&nbsp;&nbsp;/*&nbsp;to&nbsp;be&nbsp;below&nbsp;the&nbsp;parent&nbsp;element&nbsp;*/}<!DOCTYPE&nbsp;html><html><head> &nbsp;&nbsp;<meta&nbsp;charset="utf-8"> &nbsp;&nbsp;<title>Position&nbsp;a&nbsp;pseudo-element&nbsp;below&nbsp;its&nbsp;parent</title></head><body> &nbsp;&nbsp;<div&nbsp;id="element"> &nbsp;&nbsp;</div></body></html>

守着星空守着你

我知道这是个老生常谈,但我觉得有必要贴出正确的答案。这个问题的实际答案是,您需要用伪元素在元素的父元素上创建一个新的堆叠上下文(实际上您必须给它一个z索引,而不仅仅是一个位置)。就像这样:#parent&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;relative; &nbsp;&nbsp;&nbsp;&nbsp;z-index:&nbsp;1;}#pseudo-parent&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute; &nbsp;&nbsp;&nbsp;&nbsp;/*&nbsp;no&nbsp;z-index&nbsp;allowed&nbsp;*/}#pseudo-parent:after&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;position:&nbsp;absolute; &nbsp;&nbsp;&nbsp;&nbsp;top:0; &nbsp;&nbsp;&nbsp;&nbsp;z-index:&nbsp;-1;}它与使用:前置或:后伪元素无关。#parent&nbsp;{&nbsp;position:&nbsp;relative;&nbsp;z-index:&nbsp;1;&nbsp;}#pseudo-parent&nbsp;{&nbsp;position:&nbsp;absolute;&nbsp;}&nbsp;/*&nbsp;no&nbsp;z-index&nbsp;required&nbsp;*/#pseudo-parent:after&nbsp; {&nbsp;position:&nbsp;absolute;&nbsp;z-index:&nbsp;-1;&nbsp;}/*&nbsp;Example&nbsp;styling&nbsp;to&nbsp;illustrate&nbsp;*/#pseudo-parent&nbsp;{&nbsp;background:&nbsp;#d1d1d1;&nbsp;} #pseudo-parent:after&nbsp;{&nbsp;margin-left:&nbsp;-3px;&nbsp;content:&nbsp;"M"&nbsp;}<div&nbsp;id="parent"> &nbsp;<div&nbsp;id="pseudo-parent"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div></div>

素胚勾勒不出你

试试看el&nbsp;{ &nbsp;&nbsp;transform-style:&nbsp;preserve-3d;}el:after&nbsp;{ &nbsp;&nbsp;transform:&nbsp;translateZ(-1px);}
随时随地看视频慕课网APP
我要回答