我试图用:后伪元素CSS选择器样式一个元素

#element {
    position: relative;
    z-index: 1;
}

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

似乎::后面的元素不能比元素本身更低。

有没有办法让伪元素低于元素本身?


当前回答

我解决得很简单:

.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: -1;
}

这样做的是将父元素堆叠在z-index: 1处,这就给了子元素空间“结束”在z-index: 0处,因为其他dom元素“存在”在z-index: 0上。如果我们不给父元素一个z-index为1,子元素就会在其他dom元素下面,因此不可见。

这也适用于伪元素,如:after

其他回答

试试吧

el {
  transform-style: preserve-3d;
}
el:after {
  transform: translateZ(-1px);
}

我不知道是否有人会有同样的问题。所选的答案部分正确。

你需要的是:

parent{
  z-index: 1;
}
child{
 position:relative;
 backgr

我解决得很简单:

.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: -1;
}

这样做的是将父元素堆叠在z-index: 1处,这就给了子元素空间“结束”在z-index: 0处,因为其他dom元素“存在”在z-index: 0上。如果我们不给父元素一个z-index为1,子元素就会在其他dom元素下面,因此不可见。

这也适用于伪元素,如:after

这里有两个问题:

The CSS 2.1 specification states that "The :beforeand :after pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers. Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.

我能想到的唯一一件事是跨浏览器工作是使用javascript插入元素,而不是CSS。我知道这不是一个很好的解决方案,但是:before和:after伪选择器看起来并不能解决这个问题。

说到规范(http://www.w3.org/TR/CSS2/zindex.html),由于a.someSelector被定位,它创建了一个新的堆叠上下文,它的子上下文无法跳出。保留a.someSelector不定位,然后子a.someSelector:after可以定位在与a.someSelector相同的上下文中。