如何为小高度按钮实现正常的旋转边框动画?
修复小高度按钮的动画边框问题
问题描述
尝试为按钮制作动画边框,但仅当按钮高度较高时效果正常,小高度按钮表现异常。示例中高度为200px的第二个按钮运行正常,但高度为36px的第一个按钮不行,需要修复该问题以适配高度为40px左右的按钮。
原代码展示
HTML代码
<div class="button">Button</div> <div class="button">Button</div>
CSS代码
.button { width: 172px; height: 36px; position: relative; overflow: hidden; z-index: 0; border-radius: 8px; } .button:nth-child(2){ margin-top: 15px; height: 200px } .button::before { content: ""; position: absolute; z-index: -2; left: -50%; top: -50%; width: 200%; height: 200%; background-color: #002b53; background-repeat: no-repeat; background-position: 0 0; background-image: conic-gradient(transparent 20%, #fff 20%, transparent 30%); animation: rotate 4s linear infinite; } .button::after { content: ""; position: absolute; z-index: -1; left: 1px; top: 1px; border-radius: 7px; width: calc(100% - 2px); height: calc(100% - 2px); background: #f6f6f6; } @keyframes rotate { 100% { transform: rotate(1turn); } }
解决方案
问题根源在于原conic-gradient的角度设置在小高度按钮上,白色渐变区域无法刚好覆盖按钮的边框范围。调整渐变参数和伪元素的尺寸定位即可修复:
修改后的CSS代码
.button { width: 172px; height: 40px; /* 目标高度 */ position: relative; overflow: hidden; z-index: 0; border-radius: 8px; display: flex; align-items: center; justify-content: center; /* 让按钮文字居中,可选优化 */ } .button:nth-child(2){ margin-top: 15px; height: 200px } .button::before { content: ""; position: absolute; z-index: -2; left: -25%; top: -25%; width: 150%; height: 150%; background-color: #002b53; background-image: conic-gradient( transparent, transparent 30deg, #fff 30deg, #fff 60deg, transparent 60deg ); animation: rotate 4s linear infinite; } .button::after { content: ""; position: absolute; z-index: -1; left: 1px; top: 1px; border-radius: 7px; width: calc(100% - 2px); height: calc(100% - 2px); background: #f6f6f6; } @keyframes rotate { 100% { transform: rotate(1turn); } }
关键修改点
- 调整伪元素
.button::before的尺寸为150%宽高,同时将left和top设为-25%,让渐变中心更贴近按钮中心,避免小尺寸下渐变区域偏移。 - 重新定义
conic-gradient的角度:用transparent 30deg, #fff 30deg, #fff 60deg, transparent 60deg创建一个30度的白色扇形,旋转时会形成连续的边框动画,适配小高度按钮。 - 可选优化:给
.button添加display: flex和居中属性,让按钮文字布局更美观。
这样修改后,无论是40px的小按钮还是200px的大按钮,动画边框都能正常显示。
内容的提问来源于stack exchange,提问作者Maks
相关产品推荐
相关产品推荐

