直接进入主题,有这样几种渐变方法。
一、transition过渡background-color
background-img并不支持transition方法,但是background-color可以,所以可以有渐变色彩的效果实现
<style>
.box {
max-width: 400px;
height: 200px;
background: olive linear-gradient(to right, rgba(0, 255, 0, 0), rgba(0, 255, 0, .5));
transition: background-color .5s;
}
.box:hover {
background-color: purple;
}
</style>
<body>
<div class="box"></div>
</body>
二、transition过渡background
虽然background-img不支持transition,但是我们可以变相用background-position来支持transition实现渐变
<style>
.box {
max-width: 400px;
height: 200px;
background: linear-gradient(to right, olive, green, purple);
background-size: 200%;
transition: background-position .5s;
}
.box:hover {
background-position: 100% 0;
}
</style>
<body>
<div class="box"></div>
</body>
三、hover伪元素改变opacity覆盖实现“渐变”
<style>
.box {
max-width: 400px;
height: 200px;
background: linear-gradient(to right, olive, green);
position: relative;
z-index: 0;
}
.box::before {
content: '';
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: linear-gradient(to right, green, purple);
opacity: 0;
transition: opacity .5s;
z-index: -1;
}
.box:hover::before {
opacity: 1;
}
</style>
<body>
<div class="box"></div>
</body>
实际上这里是一个颜色叠加
四、借助CSS houdini中的Properties & Values API实现变化效果。
<style>
.box {
width: 20rem;
height: 20rem;
background: linear-gradient(45deg,
rgba(255, 255, 255, 1) 0%,
var(--box__color) var(--box__gradient--position));
transition: --box__color 0.5s ease, --box__gradient--position 1s 0.5s ease;
}
.box:hover {
--box__color: #baebae;
--box__gradient--position: 0%;
}
</style>
<body>
<div class="box"></div>
</body>
<script>
if (CSS.registerProperty) {
CSS.registerProperty({
name: "--box__color",
syntax: "<color>",
initialValue: "rgba(9,9,121,1)",
inherits: false
});
CSS.registerProperty({
name: "--box__gradient--position",
syntax: "<percentage>",
initialValue: "60%",
inherits: false
});
}
</script>
更多有趣的方法欢迎大佬指出