在代码中:
<!DOCTYPE html>
<html>
<head>
<style>
.parent {
position: absolute;
top:500px;
width:400px;
border:1px solid green;
}
.parent:before {
z-index:-1;
content:'';
position:absolute;
opacity:0.5;
width:400px;
height:200px;
background-image:url('wallpaper324845.jpg');
border:1px solid red;
}
.child {
Color:black;
border:1px solid black;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Hello I am child</div>
</div>
</body>
</html>
我正在尝试创建一个透明的背景,如以下线程所述:How to set opacity in parent div and not affect in child div?。
从第四个答案看代码。我如何对
.parent
和.parent:before
的使用感到困惑。我认为这将在每个父元素之前创建一个.parent:before
元素。真的很困惑,这是如何工作的? 最佳答案
:before
使用CSS创建虚拟内容,因此在上述情况下,作者使用以下摘录方式
.parent:before{
z-index:-1;
content:'';
position:absolute;
opacity:0.5;
width:400px;
height:200px;
background-image:url('wallpaper324845.jpg');
border:1px solid red;
}
他正在使用
:before
创建一个虚拟元素,然后将其放置absolute
,分配一些尺寸并分配background
,以确保其保持在div
内容以下,他使用z-index: -1;
换句话说,
:before
,:after
只是假设在span
内嵌套两个div
元素,但是通过使用pseudo
元素,您无需具有span
即可实现与伪元素相同。考虑你有这样的事情
<div>
Hello
<span></span>
</div>
div {
position: relative;
}
div span {
position: absolute;
width: 100%;
height: 100%;
background: #f00;
z-index: -1;
left: 0;
top: 0;
}
Demo
也可以使用
:before
或:after
来实现,标记保持不变,但是CSS就像div {
position: relative;
}
div:after {
content: "";
position: absolute;
width: 100%;
height: 100%;
background: #f00;
z-index: -1;
left: 0;
top: 0;
}
Demo
因此,它只是在HTML中为您节省了一个空元素,但是如果您查看上述CSS,则使用的是
content
属性,该属性始终与:before
或:after
关联,是的,即使你保持空白。另外,请注意,
:before
和:after
生成的内容是内联的,因此为了使height
,width
正常工作,如果要使其成为块级,则需要明确提及display: block;
或display: inline-block;
,但在这种特殊情况下,由于伪元素位于absolute
位置,因此不需要div:after {
content: "Hello";
margin-top: 20px; /* This wont work as pseudo is inline by default */
}
Demo
因此将其设为
block
或inline-block
Demo