带有伪类的全宽背景元素 - z-index?

时间:2016-04-08 17:30:52

标签: css pseudo-element

编辑:我发现当我删除父元素的z-index时它会起作用。无论如何...是否有更少的" hackish"如何实现这一切?它有效,但确实感觉非常hackish。

我尝试在居中的50%行后面创建一个全宽度的伪元素。它运行正常(但代码看起来非常h​​ackish)但我无法在其父代后面获得伪元素z-index:

> Visit codepen-battleground here.

这是SCSS代码:

html, body {
  height: 100%;
  margin: 0;
  overflow-x: hidden;
  overflow-y: auto;
}

.content {
  background-color: blue;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  width: 50%;
  z-index: 1;
  padding: 2em;

  &:after {
        content: "";
        display: block;
        height: 100%;
        left: -50vw;
        opacity: .7;
        position: absolute;
        right: 0vw;
        top: 0;
        width: 200vw;
        z-index: -1;
        border: 10px solid green;
        box-sizing: border-box;
        background-color: tomato;
    }
}

这样做有诀窍吗?我很乐意让这个工作。

1 个答案:

答案 0 :(得分:1)

如果您删除其工作的父级z-index

我还更改了居中解决方案,以便可以删除正文上的溢出滚动。

html, body {
  height: 100%;
  margin: 0;
}
.content {
  background-color: blue;
  margin: 0 auto;
  position: relative;
  width: 50%;
  padding: 2em;
}
.content:after {
  content: "";
  display: block;
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: 100vw;
  transform: translateX(-50%);
  z-index: -1;
  opacity: .7;
  box-sizing: border-box;
  background-color: tomato;
}
<div class="content">
  <strong>This should go to front so it's <em>blue</em> not lilac</strong> - Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</div>