CSS 中的::before 元素完全起作用了

问题描述 投票:0回答:1

我正在尝试使用

::before
更改背景图像的不透明度而不影响其他元素。但即使在不同的浏览器上它似乎也不起作用。 这是代码:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styling/style.css">
    <title>Gardening | Home</title>
</head>
<body>
<!-- header -->
    <header>
        <nav>
            <h3 class="center">Gardenizo</h3>
<!-- search icon -->
            <ul>
                <li><a href="#" class="a">Home</a></li>
                <li><a href="#" class="a">Shop</a></li>
                <li><a href="#" class="a">About</a></li>
                <li><a href="#" class="a">Contact</a></li>
                <li><a href="#" class="a">See more</a></li>
            </ul>
        </nav>
    </header>

<!-- first section -->
    <section class="land_page">
        <div class="text center">
            <p>Bring freshness into your place.</p>
            <h1>Plants are awesome!</h1>
        </div>

<!-- background image -->
        <img src="./assets/plantsbg3.jpeg" class="img" alt="">
    </section>
</body>
</html>

这是CSS:

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
/* variables */
:root{
    --header-color: white;
}



/* shared css */
.center{
    justify-content: center;
    align-items: center;
    text-align: center;
}
.a{
    text-decoration: none;
    color: black;
}


/* header */
header{
    position: relative;
    background-color: var(--header-color);
    min-height: 80px;
    box-shadow: 3px 3px 12px black;
}
header nav{
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 20px;
}
    header nav ul{
    display: flex;
    gap: .7cm;
    justify-content: center;
    list-style: none;
}


/* section 1 */
.land_page{
    width: 100%;
    min-height: 500px;
    padding-top: 1cm;
}
.land_page .text{
    position: relative;
    display: flex;
    flex-direction: column;
    margin-top: 3cm;
}
.land_page .text h1{
    font-size: 4rem;
}
.land_page img{
    width: 100%;
    display: flex;
    margin-top: -7cm; 
}

.land_page img::before{
    content: '';
    position:absolute;
    top:0px;
    left:0px;
    opacity: 10%;
}

我尝试了

$::before{ }
但还是没用。

css pseudo-element
1个回答
0
投票

您的 CSS 正在尝试在

::before
元素上设置
<img>
伪元素。但是,替换元素,例如
<img>
<input>
元素,不能有伪元素

注意: ::before 和 ::after 生成的伪元素包含在元素的格式框中,因此不适用于替换元素,例如

<img>
,或到
<br>
元素。

您可能希望将

<img>
元素包装在非替换元素(例如
<div>
)中,并使用该元素的
::before
伪元素。

© www.soinside.com 2019 - 2024. All rights reserved.