首页 > 解决方案 > 在图像顶部创建图像深色叠加层

问题描述

我有以下 HTML,其中我的横幅中有一个背景图片:

<header>
        <div class="banner">

                                
                                <p>
                                    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                                </p>

        </div>
    </header>

在我的 CSS 上:

.banner {
  position: relative;
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url('https://i.imgur.com/pXsKCUt.jpg');
  min-height: 300px;
  padding: 50px 0px;
}

现在我试图在我的图像背景上添加一个深色,所以我所做的是我使用了:before属性:

    .banner:before {
background-color: black
width: 100%;
height: auto;
opacity: 0.5;
}

但是,这并没有在图像顶部添加深色背景覆盖。

如何在 CSS 中实现这一点?

标签: htmlcss

解决方案


您需要将content属性添加到伪元素,然后将伪元素绝对定位在其父元素之上。

.banner {
  position: relative;
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url('https://i.imgur.com/pXsKCUt.jpg');
  min-height: 300px;
  padding: 50px 0px;
}

.banner:before {
  content: "";
  background-color: black;
  position: absolute;
  inset: 0;
  opacity: 0.5;
}

p {
  position: relative;
  color: white;
  padding: 1em;
}
<header>
  <div class="banner">


    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </p>

  </div>
</header>


推荐阅读