先加一个盒子.mask,把这个盒子设置尺寸(与父级盒子相同) 加渐变,渐变是透明transparent到黑色半透明rgba(0,0,0,0.5),定位到父级盒子上。默认状态下设置透明度opacity为0,鼠标悬停时设置透明度opacity为1。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>渐变背景</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
position: relative;
margin: 100px auto;
width: 300px;
height: 212px;
}
.box img {
width: 300px;
height: 212px;
}
.box .title {
position: absolute;
left: 20px;
bottom: 20px;
z-index: 1;
width: 260px;
color: #fff;
font-size: 20px;
font-weight: 700;
}
.mask {
position: absolute;
top: 0;
width: 100%;
height: 100%;
background-image: linear-gradient(transparent, rgba(0, 0, 0, 0.5));
opacity: 0;
transition: all .5s;
}
.box:hover .mask {
opacity: 1;
}
</style>
</head>
<body>
<div class="box">
<img src="./image/banner.jpg" alt="">
<div class="title">布鲁克林有棵树布鲁克林有棵树布鲁克林有棵树</div>
<div class="mask"></div>
</div>
</body>
</html>