我想在悬停时添加线性渐变过渡。
我做了一些研究,发现它是如何工作的,但遗憾的是它们仅适用于按钮等,而我想在图像上使用它。
我使用css属性 background-image 添加了图像。我希望当用户悬停图像时,图像会显示带过渡的线性渐变。
这是代码。
.project-1 {
background-image: url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
width: 350px;
height: 250px;
background-position: center;
background-size: cover;
transition: transform 0.5s , opacity 0.5s;
}
.project-1:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
background-position: center;
background-size: cover;
transform: scale(1.05);
}
<div class="project-1"></div>
我在stackoverflow上找到的主题有按钮或简单的背景,没有任何图像。
(我在代码中使用的图片仅用于代码段)
答案 0 :(得分:2)
您不能使用像这样的线性渐变应用淡入淡出过渡。另一种方法是在应用不透明度转换的位置使用伪元素:
.project-1 {
background-image: url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
width: 350px;
height: 250px;
background-position: center;
background-size: cover;
transition: transform 0.5s, opacity 0.5s;
}
.project-1:before {
content: "";
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.39);
transition: 0.5s;
opacity: 0;
}
.project-1:hover {
transform: scale(1.05);
}
.project-1:hover::before {
opacity: 1;
}
&#13;
<div class="project-1"></div>
&#13;
或者您可以通过播放背景大小或背景位置来实现渐变的另一种过渡。这是一个例子:
.project-1 {
background-image:
linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
width: 350px;
height: 250px;
background-position:0 0,center;
background-size:100% 0%,cover;
background-repeat:no-repeat;
transition: 0.5s;
}
.project-1:hover {
background-image:
linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
background-size:100% 100% ,cover;
transform: scale(1.05);
}
&#13;
<div class="project-1"></div>
&#13;