使用伪元素创建背景叠加

fil*_*d13 30 html css pseudo-element

我的目标是使用任何背景的div,然后使用伪元素创建透明的白色叠加,从而"淡化"div的背景.但是,"叠加"必须在div的内容之下.因此,在以下示例中:

<div class="container">
    <div class="content">
        <h1>Hello, World</h1>
    </div>
</div>

.container {
    background-color: red;
    width: 500px;
    height: 500px;
    position: relative;
}
.content {
    background-color: blue;
    width: 250px;
}
.container::before {
    content:"";
    display: block;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1;
    background-color: rgba(255, 255, 255, .8);
}
Run Code Online (Sandbox Code Playgroud)

.content div不应该是"下面"的白色覆盖,又名.container::before.

我宁愿不必使用z-index.content,但我可以的,如果这是唯一的解决方案.

最终目标:应该覆盖红色而文本和蓝色不应该覆盖.

JS小提琴:http://jsfiddle.net/1c5j9n4x/

Jos*_*ier 31

如果伪元素具有a z-index,则需要定位.content元素并添加z-index值以建立堆叠上下文.

更新的示例

.content {
    background-color: blue;
    width: 250px;
    position: relative;
    z-index: 1;
}
Run Code Online (Sandbox Code Playgroud)

..你可以z-index从伪元素中删除,然后只是定位.content元素.这样做,没有一个元素需要z-index.这样做的原因是因为:before伪元素本质上是前一个兄弟元素.因此,后续.content元件位于顶部.

替代例子

.content {
    background-color: blue;
    width: 250px;
    position: relative;
}
.container::before {
    content:"";
    display: block;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    background-color: rgba(255, 255, 255, .8);
}
Run Code Online (Sandbox Code Playgroud)