【问题标题】:CSS: How to remove a tint with a transition from a background image on hover?CSS:如何在悬停时从背景图像中删除带有过渡的色调?
【发布时间】:2020-09-10 17:47:11
【问题描述】:
我有以下 HTML 和 CSS 示例,其中有一个带有红色的图像。当我将鼠标悬停在它上面时,色调被移除 - 这是通过再次插入没有色调的图像来实现的。
问题在于它是非常瞬时的 - 没有过渡。我试图插入一个过渡,但它似乎不起作用。
div {
background-image: linear-gradient(to bottom,
rgba(250, 0, 0, 0.5),
rgba(250, 0, 0, 0.5)), url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
height: 300px;
width: 300px;
background-size: 300px;
transition: all 2s ease-out;
}
div:hover {
background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
transition: all 2s ease-out;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
</div>
</body>
</html>
【问题讨论】:
标签:
html
css
animation
css-transitions
【解决方案1】:
有些 CSS 属性是 animatable,有些不是。很遗憾,您不能将transition 应用于background-image,但您仍然可以选择:
你可以使用box-shadow来达到想要的效果:
div {
background: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png") 50% / 300px;
height: 300px;
width: 300px;
box-shadow: inset 0 0 0 150px #f008;
transition: 1s ease-out;
}
div:hover {
box-shadow: inset 0 0 0 150px #0000;
}
<div></div>
如果you're open to,则使用background-blend-mode:
div {
background:#f008 url("https://homepages.cae.wisc.edu/~ece533/images/cat.png") 50% / 300px;
background-blend-mode: overlay;
height: 300px;
width: 300px;
transition: 1s ease-out;
}
div:hover {
background-color:#0000;
}
<div></div>
另一个选项是使用border:
div {
background:url("https://homepages.cae.wisc.edu/~ece533/images/cat.png") 50% / 300px;
border:solid 150px #f008;
box-sizing:border-box;
height: 300px;
width: 300px;
transition: 1s ease-out;
}
div:hover {
border-color:#0000;
}
<div></div>
或者您可以使用绝对定位(伪)元素,正如其他答案所建议的那样。
希望对你有帮助。
【解决方案2】:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.elem1 {
background-image: linear-gradient(
to bottom,
rgba(250, 0, 0, 0.5),
rgba(250, 0, 0, 0.5)
),
url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
height: 300px;
width: 300px;
background-size: 300px;
transition: all 2s;
position: relative;
}
.elem2 {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
opacity: 0;
background-size: cover;
}
.elem2:hover {
transition: all 2s;
opacity: 1;
}
</style>
</head>
<body>
<div class="elem1">
<div class="elem2"></div>
</div>
</body>
</html>
【解决方案3】:
您正在尝试为 background-image 设置动画,但这是无法完成的,
为什么不使用after 伪元素来代替
div {
background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
height: 300px;
width: 300px;
background-size: 300px;
position: relative;
}
div:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
background-color: red;
opacity: 0.5;
transition: .5s;
}
div:hover:after {
opacity: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
</div>
</body>
</html>