使用Tailwind CSS:绝对定位居中元素无法正常旋转的问题求助
问题原因及解决办法
问题出在animate-spin的变换会覆盖平移样式。Tailwind的animate-spin关键帧是直接设置transform: rotate(0deg)和transform: rotate(360deg),这会替换掉你通过-translate-x-1/2 -translate-y-1/2添加的平移变换。
没有了平移,元素的左上角会停在容器的left-1/2 top-1/2位置,旋转时会绕自身左上角转动,看起来就像是沿斜方向移动,而不是绕中心旋转。
解决办法有两种:
方法一:用inset-0 m-auto替代平移居中
不需要left-1/2、top-1/2和translate类,直接用以下写法:
<svg class="absolute inset-0 m-auto animate-spin">...</svg>
inset-0会让元素填满容器,m-auto则会自动把元素挤到容器中心,此时再添加animate-spin,元素会绕自身中心正常旋转。
方法二:自定义包含平移的旋转动画
如果一定要用left-1/2 top-1/2的方式,就需要修改动画,让它同时包含平移和旋转:
- 在
tailwind.config.js里扩展动画:
module.exports = { theme: { extend: { animation: { 'spin-center': 'spin-center 1s linear infinite', }, keyframes: { 'spin-center': { 'from': { transform: 'translate(-50%, -50%) rotate(0deg)' }, 'to': { transform: 'translate(-50%, -50%) rotate(360deg)' }, }, }, }, }, }
- 然后使用自定义动画:
<svg class="absolute left-1/2 top-1/2 animate-spin-center">...</svg>
这样动画里的transform会同时保留平移和旋转,元素就能在居中的状态下正常旋转了。
内容的提问来源于stack exchange,提问作者KenB
相关产品推荐
相关产品推荐

