Variants
变体指的就是一定条件下应用某些类名。
Tailwind
中的每个实用程序类都可以通过在类名的开头添加一个变体来有条件地应用,该变体描述了想要针对的条件。
内置变体如下:
Pseudo-classes
伪类,譬如:hover
、:focus
、:first-child
和:required
;Pseudo-elements
伪元素,譬如::before
、::after
、::selection
和::placeholder
;Media and feature queries
媒体和功能查询,譬如响应断点、暗模式和prefers-reduced-motion
;Attribute selectors
属性选择器,譬如[dir="rtl"]
和[open]
;Child selectors
子选择器,譬如& > *
和& *
。
TIP
Variants
变体,会改变类名。
譬如,dark:bg-red-500
会被编译为:
css
.dark\:bg-red-500:where(.dark, .dark *) {
background-color: var(--color-red-500);
}
那么实际类名会是 .dark\:bg-red-500
,当需要自定义某类名,从而覆盖样式时,这一点需要额外注意。
1.Pseudo-classes
2.Pseudo-elements
3.Media and feature queries
媒体和功能查询Media and feature queries
4.Attribute selectors
属性选择器Attribute selectors
5.Child selectors
子选择器Child selectors
ps.Custom variants
此处重点记录下自定义变体Custom variants。
任意变体的用法与任意值arbitrary values的用法类似。
任意变体只是用方括号括起来的表示选择器的格式字符串。
例如,当元素具有 is-dragging
类时,以下任意变体会将光标更改为 grabbing
:
html
<ul role="list">
{#each items as item}
<li class="[&.is-dragging]:cursor-grabbing">{item}</li>
{/each}
</ul>
如果选择器中需要空格,可以使用下划线。例如,以下任意变体将选择添加了该类的元素内的所有 p
元素:
html
<div class="[&_p]:mt-4">
<p>Lorem ipsum...</p>
<ul>
<li>
<p>Lorem ipsum...</p>
</li>
<!-- ... -->
</ul>
</div>
如果在项目中多次使用相同的任意变体,则可能值得使用 @custom-variant
指令创建自定义变体:
css
@custom-variant theme-midnight (&:where([data-theme="midnight"] *));
然后这样使用:
html
<html data-theme="midnight">
<button class="theme-midnight:bg-black ..."></button>
</html>