常见状态前缀
·
状态处理概述
Tailwind CSS 通过实用类(utility classes)处理元素的不同状态(如悬停、聚焦、激活等),无需编写自定义 CSS。状态类通过前缀(如 hover:、focus:)与基础类结合,实现动态样式。
常见状态前缀
-
交互状态
hover:悬停状态(如hover:bg-blue-500)focus:聚焦状态(如focus:ring-2)active:点击激活状态(如active:scale-95)group-hover:父容器悬停时生效(需配合group类) -
表单状态
checked:复选框/单选选中状态(如checked:bg-green-500)disabled:禁用状态(如disabled:opacity-50) -
媒体查询
sm:、md:、lg:等响应式断点前缀(如md:text-lg)
使用示例
悬停与聚焦效果
<button class="bg-gray-300 hover:bg-blue-500 focus:ring-2 focus:ring-blue-600">
Click Me
</button>
父容器悬停控制子元素
<div class="group">
<div class="text-gray-500 group-hover:text-red-500">Hover over parent</div>
</div>
表单元素状态
<input type="checkbox" class="checked:bg-green-500 disabled:opacity-30">
自定义状态
通过 @variants 指令扩展自定义状态(需在 Tailwind 配置文件中定义):
@variants motion-safe {
.animate-slow {
animation: spin 3s linear infinite;
}
}
使用:<div class="motion-safe:animate-slow">
状态叠加顺序
Tailwind 遵循 CSS 层叠规则。多个状态前缀可组合使用,但需注意顺序优先级(如 focus:hover:bg-purple-500 表示聚焦且悬停时的样式)。
注意事项
- 启用状态类:某些状态(如
focus:、disabled:)需在tailwind.config.js的variants中显式启用。 - 性能优化:避免滥用状态类,尤其是复杂动画或高频交互场景。
通过合理使用状态前缀,可以高效实现动态 UI 效果,减少自定义 CSS 代码量。
更多推荐



所有评论(0)