Skip to content

Tailwind CSS - 旋转

rotate 工具类是 Tailwind 变换(transform)系列的一部分,允许你顺时针或逆时针旋转元素。它非常适合创建视觉效果、旋转图标或构建加载指示器等动画。

Tailwind 提供了一系列 rotate-{degree} 和 -rotate-{degree} 类,用于常用旋转值。对于自定义旋转,你可以使用任意值。

ClassCSS Properties
rotate-0transform: rotate(0deg);
rotate-1transform: rotate(1deg);
rotate-2transform: rotate(2deg);
rotate-6transform: rotate(6deg);
rotate-12transform: rotate(12deg);
rotate-45transform: rotate(45deg);
rotate-90transform: rotate(90deg);
rotate-180transform: rotate(180deg);
-rotate-45transform: rotate(-45deg);

旋转平滑应用时效果最佳。将 rotate-* 类与 hover: 等状态变体以及过渡工具类(transition、duration-*、ease-*)结合使用,以创建优雅的交互效果。

以下示例演示了如何在悬停时巧妙地旋转卡片。一张卡片顺时针旋转(hover:rotate-3),另一张逆时针旋转(hover:-rotate-3)。transition-transform 和 duration-300 类确保旋转在 300 毫秒内平滑动画。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind CSS Rotate</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 flex items-center justify-center min-h-screen">
<div class="flex flex-col sm:flex-row gap-8">
<!-- 卡片 1:悬停时顺时针旋转 -->
<div class="w-48 h-64 bg-white rounded-lg shadow-xl p-6 flex items-center justify-center
transition-transform duration-300 ease-in-out hover:rotate-3">
<span class="font-bold text-slate-700">Hover Me</span>
</div>
<!-- 卡片 2:悬停时逆时针旋转 -->
<div class="w-48 h-64 bg-white rounded-lg shadow-xl p-6 flex items-center justify-center
transition-transform duration-300 ease-in-out hover:-rotate-3">
<span class="font-bold text-slate-700">Hover Me</span>
</div>
</div>
</body>
</html>

对于连续旋转,例如加载指示器(loading spinner),Tailwind 提供了 animate-spin 工具类。此类应用一个 CSS 动画,使元素连续旋转 360 度。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind CSS Loading Spinner</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-900 flex items-center justify-center min-h-screen">
<div class="flex items-center gap-4 text-white">
<svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span>Loading...</span>
</div>
</body>
</html>

如果你需要一个默认主题中没有的特定旋转角度,你可以使用 Tailwind 的 JIT 引擎即时生成它。只需使用方括号传入自定义值即可。

  • 示例:class="rotate-[17deg]" 将应用 transform: rotate(17deg);。
  • 负值:class="-rotate-[22.5deg]" 将应用 transform: rotate(-22.5deg);。