如何用SCSS实现渐变按钮Hover时360度无限旋转效果
实现按钮悬停时渐变边框360度无限旋转
我主页里有个按钮,想要实现鼠标悬停时按钮的渐变边框360度无限旋转效果,目前自己的SCSS水平搞不定,希望能让主页更出彩。以下是我的JSX和SCSS代码:
我的JSX代码:
<section className='section-cover'> <div className='cover-title'> <h1>Blah Blah, Blah Blah </h1> <h2>You never have to do it yourself again, Blah Blah Blah Blah and let someone do the work for you.</h2> <button className='try-out'>Try Us Out</button> </div> <img className='cuttingBlah' src={cuttingBlah}/> </section>
我的SCSS代码:
.section-cover { margin-top: 60px; display: flex; flex-direction: row; justify-content: flex-end; align-items: center; background-color: transparent; padding: 50px 100px; position: relative; z-index: 1; ::before, ::after { content: ''; position: absolute; inset: 0; background: linear-gradient( 0deg, var(--color-2), var(--color-3), var(--color-4), var(--color-5), var(--color-6), ); z-index: -1; } ::before { filter: blur(0.5rem); } .cover-title { z-index: 2; h1, h2 { color: black; margin: 0px; } h1 { font-size: 55px; margin-bottom: 30px; } .try-out { box-sizing: content-box; font-weight: bold; font-size: large; padding: 1rem 2rem; cursor: pointer; position: relative; border: 10px solid transparent; background: linear-gradient(white, white) padding-box, linear-gradient( to right, #5ddcff, #3c67e3 43%, #4e00c2) border-box; border-radius: 20px; margin-top: 20px; overflow: hidden; transition: transform 0.5s ease; } } .cuttingBlah { border-radius: 10px; width: 520px; z-index: 2; } }
解决方案
要实现渐变边框的无限旋转,需要借助CSS动画和伪元素来实现,直接旋转border渐变的方式难以操作。修改后的.try-out部分SCSS代码如下:
.try-out { box-sizing: content-box; font-weight: bold; font-size: large; padding: 1rem 2rem; cursor: pointer; position: relative; border: 10px solid transparent; background: linear-gradient(white, white) padding-box; border-radius: 20px; margin-top: 20px; overflow: hidden; transition: transform 0.5s ease; // 伪元素实现旋转渐变背景 &::before { content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%; background: linear-gradient( to right, #5ddcff, #3c67e3 43%, #4e00c2, #5ddcff ); z-index: -1; opacity: 0; transition: opacity 0.3s ease; animation: rotate 3s linear infinite; } // 悬停时显示渐变旋转效果 &:hover::before { opacity: 1; } // 裁剪出按钮内部白色区域,模拟边框效果 &::after { content: ''; position: absolute; inset: 10px; // 与按钮border宽度保持一致 background: white; border-radius: 10px; // 原border-radius减去border宽度 z-index: -1; } } // 定义360度旋转动画 @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
关键说明
- 用
::before伪元素创建一个超出按钮范围的渐变背景,宽高设为200%避免旋转时露出空白区域 - 初始状态下伪元素透明度为0,hover时切换为1,配合动画实现渐变旋转的显隐过渡
::after伪元素填充白色并裁剪出内部区域,保证按钮内容区的白色背景不受渐变影响- 动画时长可以通过调整
3s参数来控制旋转速度
内容的提问来源于stack exchange,提问作者Hatter7474
相关产品推荐
相关产品推荐

