html - 在图像顶部创建图像深色叠加层
问题描述
我有以下 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 中实现这一点?
解决方案
您需要将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>
推荐阅读
- javascript - 无法在 Firefox for Android 中激活 navigator.storage.persist
- spring-boot - HttpServletRequest 返回 emty 阅读器
- html - 如何通过动态更改将电子表格链接到 wordpress?
- javascript - React JS + Azure MVC:进行 API 调用时 POST 404(未找到)
- kotlin - 如何访问 Kotlin 中函数内的主构造函数变量?
- python - 关于网格的 Python tkinter 几何管理
- java - Android Speech to text 后台服务
- android - RecyclerView 和 LiveData
- php - 创建具有相同键检查点的多维 PHP 数组
- ios - 如何从 json 解析成 Core Data 模型,其中有一个带有关联值的枚举?