使用伪元素创建背景叠加 [英] Use Pseudo Element to Create Background Overlay

查看:85
本文介绍了使用伪元素创建背景叠加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是拥有一个带有任何背景的div,然后使用伪元素创建一个透明的白色覆盖,从而减轻div的背景。 overlay必须在div的内容下,虽然。因此,在以下示例中:

My goal is to have a div with any background, which then uses a pseudo element to create a transparent white overlay, thus "lightening" the background of the div. The "overlay" must be UNDER the contents of the div, though. So, in the following example:

<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);
}

.content div 不应该是下面白色覆盖,也就是 .container :: before

The .content div should not be "underneath" the white overlay, aka .container::before.

我不想在 .content 上使用 z-index c $ c>,但我可以,如果这是唯一的解决方案。

I would prefer not having to use z-index on .content, but I can if that is the only solution.

最终目标:红色应该覆盖,而文字和蓝色不覆盖。

End goal: The red should be covered while the text and blue are not.

JS fiddle: a href =http://jsfiddle.net/1c5j9n4x/> http://jsfiddle.net/1c5j9n4x/

JS fiddle: http://jsfiddle.net/1c5j9n4x/

推荐答案

如果伪元素有 z-index ,那么您需要将 .content 元素,并向建立堆叠上下文添加 z-index

If the pseudo element has a z-index, then you would need to position the .content element and add a z-index value to establish a stacking context.

更新示例

.content {
    background-color: blue;
    width: 250px;
    position: relative;
    z-index: 1;
}

您可以 c $ c> z-index ,然后只定位 .content 元素。这样做时,没有元素需要 z-index 。这样做的原因是因为:before 伪元素本质上是先前的同级元素。因此,后续的 .content 元素位于顶部。

..you could also remove the z-index from the pseudo element and then merely position the .content element. In doing so, none of the elements need a z-index. The reason this works is because the :before pseudo element is essentially a previous sibling element. Thus, the succeeding .content element is positioned on top.

替代示例

.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);
}

这篇关于使用伪元素创建背景叠加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆