Html 使用伪元素创建背景叠加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28121731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Pseudo Element to Create Background Overlay
提问by fildred13
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,然后使用伪元素创建透明的白色叠加层,从而“照亮”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);
}
The .content
div
should not be "underneath" the white overlay, aka .container::before
.
本.content
div
不应该是“下面”的白色覆盖,又名.container::before
。
I would prefer not having to use z-index
on .content
, but I can if that is the only solution.
我宁愿不必使用z-index
on .content
,但如果这是唯一的解决方案,我可以。
End goal: The red should be covered while the text and blue are not.
最终目标:红色应该被覆盖,而文本和蓝色则不被覆盖。
JS fiddle: http://jsfiddle.net/1c5j9n4x/
JS小提琴:http: //jsfiddle.net/1c5j9n4x/
回答by Josh Crozier
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.
如果伪元素具有z-index
,则您需要定位该.content
元素并添加一个z-index
值以建立堆叠上下文。
.content {
background-color: blue;
width: 250px;
position: relative;
z-index: 1;
}
..you couldalso 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.
..你也可以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);
}