如何在Tailwind CSS中实现draw circle边框动画效果
Tailwind CSS实现圆形绘制边框动画方案
实现思路
- 该动画涉及伪元素多属性分步延迟过渡,无法100%通过Tailwind默认工具类实现,可将基础样式全部用原生Tailwind类实现,仅将特殊过渡逻辑做少量自定义,最大程度复用Tailwind能力。
- 提供两种实现方式,可根据项目复用需求选择。
方案1:最小侵入式(无需修改Tailwind配置)
基础样式全部用Tailwind原生类编写,仅将无法复用的过渡逻辑写在样式文件中:
HTML代码
<button class="w-20 h-20 p-0 rounded-full hover:text-blue-500 relative before:content-[''] before:absolute before:inset-0 before:rounded-full before:border-2 before:border-transparent after:content-[''] after:absolute after:inset-0 after:rounded-full after:border-0 after:border-transparent spin-circle"> Spin Circle </button>
自定义CSS代码
/* 仅实现特殊过渡逻辑,样式规则复用Tailwind能力 */ .spin-circle:hover::before { @apply border-t-blue-500 border-r-blue-500 border-b-blue-500; transition: border-top-color 0.15s linear, border-right-color 0.15s linear 0.1s, border-bottom-color 0.15s linear 0.2s; } .spin-circle:hover::after { @apply border-t-blue-500 border-l-2 border-r-2 rotate-[270deg]; transition: transform 0.4s linear 0s, border-left-width 0s linear 0.35s; }
方案2:全配置式(多场景复用)
将逻辑扩展到Tailwind配置中,使用时直接调用工具类即可,无需额外写CSS:
tailwind.config.js配置
/** @type {import('tailwindcss').Config} */ const plugin = require('tailwindcss/plugin') module.exports = { theme: { extend: {}, }, plugins: [ plugin(function({ addUtilities }) { addUtilities({ '.spin-circle': { width: '5em', height: '5em', padding: 0, borderRadius: '100%', position: 'relative', '&::before, &::after': { content: "''", position: 'absolute', inset: 0, borderRadius: '100%' }, '&::before': { border: '2px solid transparent' }, '&::after': { border: '0 solid transparent' }, '&:hover': { color: '#3b82f6' }, '&:hover::before': { 'border-top-color': '#3b82f6', 'border-right-color': '#3b82f6', 'border-bottom-color': '#3b82f6', 'transition': 'border-top-color 0.15s linear, border-right-color 0.15s linear 0.1s, border-bottom-color 0.15s linear 0.2s' }, '&:hover::after': { 'border-top': '2px solid #3b82f6', 'border-left-width': '2px', 'border-right-width': '2px', 'transform': 'rotate(270deg)', 'transition': 'transform 0.4s linear 0s, border-left-width 0s linear 0.35s' } } }) }) ] }
使用方式
<button class="spin-circle">Spin Circle</button>
内容的提问来源于stack exchange,提问作者Evaldas Karpys
相关产品推荐
相关产品推荐

