试图使背景图像平滑地淡出到透明状态,同时保持文本不透明度不变,但我只进行了一次开/关转换。不透明度的转换在这里不起作用,因为我需要文本保持不透明。有什么想法吗?
这是我的代码:
.grid {
margin: 0;
padding: 0;
width: 500px;
height: 250px;
}
.flexbox {
display: flex;
flex-wrap: wrap;
flex-direction: row;
overflow: hidden;
}
#one {
width: 250px;
height: 250px;
background-color: red;
background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
background-repeat: no-repeat;
background-position: 40%;
}
#one:hover {
background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
background-repeat: no-repeat;
background-position: 40%;
height: 250px;
}
<div class="grid">
<div class="flexbox">
<div id="one">
<div id="textbox">
I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
</div>
</div>
</div>
</div>
您可以尝试使用::after标记,这将帮助您实现预期效果。
您必须记住content=",否则图片将不会出现。还要记住正确设置负责图层位置的z索引。
以下是您的示例的解决方案:
.grid {
margin: 0;
padding: 0;
width: 500px;
height: 250px;
}
.flexbox {
display: flex;
flex-wrap: wrap;
flex-direction: row;
overflow: hidden;
}
#one {
width: 250px;
height: 250px;
position: relative;
}
#one::after {
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
background-repeat: no-repeat;
background-position: 40%;
left: 0;
top: 0;
content: "";
transition: opacity 0.3s, visibility 0.3s;
}
#textbox {
z-index: 2;
position: relative;
}
#one:hover::after {
opacity: 0;
transition: opacity 0.3s, visibility 0.3s;
}
<div class="grid">
<div class="flexbox">
<div id="one">
<div id="textbox">
I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
</div>
</div>
</div>
</div>