在代码中:

<!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生成的内容是内联的,因此为了使heightwidth正常工作,如果要使其成为块级,则需要明确提及display: block;display: inline-block;,但在这种特殊情况下,由于伪元素位于absolute位置,因此不需要

div:after {
    content: "Hello";
    margin-top: 20px; /* This wont work as pseudo is inline by default */
}


Demo



因此将其设为blockinline-block

Demo

10-07 19:14
查看更多