html - 如何将色调(悬停时)应用于背景图像大小设置为包含的 div?
问题描述
我有一个带有背景图像的 div。由于设计限制,背景图像需要设置为包含的大小。我想在悬停时对该图像应用色调,但是我设置它的方式意味着整个 div 色调而不仅仅是图像。
我想知道是否有一种我不知道的 CSS 技术来实现我需要的效果,只有背景图像本身着色而不是整个 div?
.image {
position: relative;
padding-top: 50%;
background-image: url('https://specials-images.forbesimg.com/imageserve/5f9cca07d4c42920d4d348c7/960x0.jpg?fit=scale');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.image::before {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.3);
opacity: 0;
transition: ease opacity 350ms;
z-index: 9;
width: 100%;
height: 100%;
}
.container:hover .image::before {
opacity: 1;
}
<div class="container">
<div class="image"></div>
</div>
解决方案
.image {
position: relative;
padding-top: 50%;
background-image: url('https://specials-images.forbesimg.com/imageserve/5f9cca07d4c42920d4d348c7/960x0.jpg?fit=scale');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.image::before {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.3);
opacity: 0;
transition: ease opacity 350ms;
z-index: 9;
width: 100%;
height: 100%;
}
.extraLayer {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: transparent;
opacity: 0;
transition: ease opacity 350ms;
z-index: 10;
width: 100%;
height: 100%;
text-align:center;
margin-top:100px;
}
.container:hover .image::before {
opacity: 1;
}
.container:hover .extraLayer {
opacity: 1;
}
<div class="container">
<div class="image"></div>
<div class="extraLayer">
<p style="color:white;">
Draw what you want
</p>
</div>
</div>
推荐阅读
- mysql - MySQL 配置文件单位差异
- python - 根据交替列从 pandas DataFrame 中删除行
- excel - 在 Range 变量中连接 For 循环计数器
- css - 带有盒子阴影的 div 的 ZigZag 底部边框
- react-native - 未定义不是对象(评估'props.contacts.reduce') - React Native
- python - Python heappush vs simple append - 有什么区别?
- java - JPanel 仅在 for 循环完成后更新
- python - 如何在 python 的递归函数中定义共享列表?
- reactjs - React js 鹅毛笔图片上传
- ios - Swift Combine 完成按钮点击