Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

html - Use Pseudo Element to Create Background Overlay

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

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

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: http://jsfiddle.net/1c5j9n4x/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Updated Example

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

..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.

Alternative Example

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...