前置知识
- 首先需要找到一个提供渐变色 css 的网站 点这里
- 了解伪元素的使用方法 ::before
- 了解 css3 过渡 transition
- 了解 css3 背景渐变 background-image
如何在 hover 时 给背景增加过渡
css3 无法对 background-image 进行过渡 所以无法使用 transition : background-image 0.6s
我们可以通过对元素增加一个相同大小的伪元素 通过用户 hover 时 切换父元素 和 伪元素的透明度 由于可以给 opacity
增加过渡效果 从而达到预期效果
代码展示
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>A beautiful button</title>
<style>
.button {
/* 相对定位 让伪元素 利用button父元素元素进行定位 */
position: relative;
padding: 10px 30px;
font-size: 18px;
font-weight: bold;
color: #fff;
border: none;
border-radius: 8px;
/* 给button 一个过渡效果*/
transition: all 0.6s ease-in-out;
cursor: pointer;
/* 指定一个 z-index 不能让伪元素的z坐标值大于button 不然字体就会被伪元素覆盖*/
z-index: 0;
/* 背景渐变色 */
background-image: linear-gradient(300deg, #00dbde 0%, #6284ff 50%, #ff0000 100%);
}
.button:hover {
transform: translateY(-3px);
}
.button::before {
content: "";
/* 伪元素 占满整个父元素button */
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
/* 开始时 伪元素的透明度位 0 完全透明 */
opacity: 0;
z-index: -1;
border-radius: 8px;
/* 给透明度增加过渡 */
transition: opacity 0.6s ease-in-out;
background-image: linear-gradient(135deg, #00dbde 0%, #6284ff 50%, #ff0000 100%);
}
.button:hover::before {
/* 在button hover 后 让伪元素的透明度为1 完全不透明 */
opacity: 1;
}
</style>
</head>
<body>
<button class="button">Hover me</button>
</body>
</html>
效果图: