1. 核心概念
  2. 悬停、聚焦和其他状态

核心概念

悬停、聚焦和其他状态

使用工具类在悬停、聚焦等状态下为元素设置样式。

Tailwind 中的每个实用类都可以通过在类名开头添加描述目标条件的变体来有条件地应用。

🌐 Every utility class in Tailwind can be applied conditionally by adding a variant to the beginning of the class name that describes the condition you want to target.

例如,要在悬停时应用 bg-sky-700 类,请使用 hover:bg-sky-700 类:

🌐 For example, to apply the bg-sky-700 class on hover, use the hover:bg-sky-700 class:

将鼠标悬停在此按钮上以查看背景颜色变化

<button class="bg-sky-500 hover:bg-sky-700 ...">Save changes</button>
这与传统的 CSS 比较如何?

以传统方式编写 CSS 时,单个类名会根据当前状态执行不同的操作:

🌐 When writing CSS the traditional way, a single class name would do different things based on the current state:

传统上,相同的类名在悬停时会应用不同的样式

.btn-primary {  background-color: #0ea5e9;}.btn-primary:hover {  background-color: #0369a1;}

在 Tailwind 中,与其在现有类上添加悬停状态的样式,不如向元素添加另一个类,这个类只在悬停时起作用:

🌐 In Tailwind, rather than adding the styles for a hover state to an existing class, you add another class to the element that only does something on hover:

在 Tailwind 中,默认状态和悬停状态使用不同的类

.bg-sky-500 {  background-color: #0ea5e9;}.hover\:bg-sky-700:hover {  background-color: #0369a1;}

注意 hover:bg-sky-700 :hover 状态定义了样式吗?默认情况下它不会做任何事情,但一旦你将鼠标悬停在具有该类的元素上,背景色就会变为 sky-700

🌐 Notice how hover:bg-sky-700 only defines styles for the :hover state? It does nothing by default, but as soon as you hover over an element with that class, the background color will change to sky-700.

这就是我们说实用类可以 有条件 应用的意思——通过使用变体,你可以精确控制你的设计在不同状态下的表现,而无需离开你的 HTML。

🌐 This is what we mean when we say a utility class can be applied conditionally — by using variants you can control exactly how your design behaves in different states, without ever leaving your HTML.

Tailwind 包含几乎所有你所需的变体,包括:

🌐 Tailwind includes variants for just about everything you'll ever need, including:

这些变体甚至可以堆叠以针对更具体的情况,例如在中等断点处、悬停时在夜间模式下更改背景颜色:

🌐 These variants can even be stacked to target more specific situations, for example changing the background color in dark mode, at the medium breakpoint, on hover:

<button class="dark:md:hover:bg-fuchsia-600 ...">Save changes</button>

在本指南中,你将了解框架中可用的每个变体,如何将它们与你自己的自定义类一起使用,甚至如何创建自己的变体。

🌐 In this guide you'll learn about every variant available in the framework, how to use them with your own custom classes, and even how to create your own.

伪类(Pseudo-classes)

:hover、:focus 和 :active(:hover, :focus, and :active)

使用 hoverfocusactive 变体时的悬停、聚焦和激活样式元素:

🌐 Style elements on hover, focus, and active using the hover, focus, and active variants:

尝试与此按钮互动以查看悬停、聚焦和激活状态

<button class="bg-violet-500 hover:bg-violet-600 focus:outline-2 focus:outline-offset-2 focus:outline-violet-500 active:bg-violet-700 ...">  Save changes</button>

Tailwind 还包括适用于其他交互状态的变体,例如 :visited:focus-within:focus-visible 等。

🌐 Tailwind also includes variants for other interactive states like :visited, :focus-within, :focus-visible, and more.

查看 伪类参考 以获取可用伪类变体的完整列表。

🌐 See the pseudo-class reference for a complete list of available pseudo-class variants.

:first、:last、:odd 和 :even(:first, :last, :odd, and :even)

使用 firstlast 变体为第一个或最后一个子元素设置样式:

🌐 Style an element when it is the first-child or last-child using the first and last variants:

  • Kristen Ramos

    kristen.ramos@example.com

  • Floyd Miles

    floyd.miles@example.com

  • Courtney Henry

    courtney.henry@example.com

  • Ted Fox

    ted.fox@example.com

<ul role="list">  {#each people as person}    <!-- Remove top/bottom padding when first/last child -->    <li class="flex py-4 first:pt-0 last:pb-0">      <img class="h-10 w-10 rounded-full" src={person.imageUrl} alt="" />      <div class="ml-3 overflow-hidden">        <p class="text-sm font-medium text-gray-900 dark:text-white">{person.name}</p>        <p class="truncate text-sm text-gray-500 dark:text-gray-400">{person.email}</p>      </div>    </li>  {/each}</ul>

你也可以使用 oddeven 变体在元素是奇数或偶数子元素时进行样式设置:

🌐 You can also style an element when it's an odd or even child using the odd and even variants:

NameTitleEmail
Jane CooperRegional Paradigm Technicianjane.cooper@example.com
Cody FisherProduct Directives Officercody.fisher@example.com
Leonard KrasnerSenior Designerleonard.krasner@example.com
Emily SelmanVP, Hardware Engineeringemily.selman@example.com
Anna RobertsChief Strategy Officeranna.roberts@example.com
<table>  <!-- ... -->  <tbody>    {#each people as person}      <!-- Use different background colors for odd and even rows -->      <tr class="odd:bg-white even:bg-gray-50 dark:odd:bg-gray-900/50 dark:even:bg-gray-950">        <td>{person.name}</td>        <td>{person.title}</td>        <td>{person.email}</td>      </tr>    {/each}  </tbody></table>

使用 nth-*nth-last-* 变体根据子元素在列表中的位置进行样式设置:

🌐 Use the nth-* and nth-last-* variants to style children based on their position in the list:

<div class="nth-3:underline">  <!-- ... --></div><div class="nth-last-5:underline">  <!-- ... --></div><div class="nth-of-type-4:underline">  <!-- ... --></div><div class="nth-last-of-type-6:underline">  <!-- ... --></div>

默认情况下,你可以向这些传递任意数量的参数,并且可以对更复杂的表达式如 nth-[2n+1_of_li] 使用任意值。

🌐 You can pass any number you want to these by default, and use arbitrary values for more complex expressions like nth-[2n+1_of_li].

Tailwind 还包括其他结构伪类的变体,例如 :only-child:first-of-type:empty 等。

🌐 Tailwind also includes variants for other structural pseudo-classes like :only-child, :first-of-type, :empty, and more.

查看 伪类参考 以获取可用伪类变体的完整列表。

🌐 See the pseudo-class reference for a complete list of available pseudo-class variants.

:required 和 :disabled(:required and :disabled)

使用 requiredinvaliddisabled 等变体来为不同状态的表单元素设置样式:

🌐 Style form elements in different states using variants like required, invalid, and disabled:

尝试使电子邮件地址有效,看看样式如何变化

<input  type="text"  value="tbone"  disabled  class="invalid:border-pink-500 invalid:text-pink-600 focus:border-sky-500 focus:outline focus:outline-sky-500 focus:invalid:border-pink-500 focus:invalid:outline-pink-500 disabled:border-gray-200 disabled:bg-gray-50 disabled:text-gray-500 disabled:shadow-none dark:disabled:border-gray-700 dark:disabled:bg-gray-800/20 ..."/>

使用此类变量可以减少模板中的条件逻辑数量,让你无论输入处于何种状态都可以使用同一组类,并让浏览器为你应用正确的样式。

🌐 Using variants for this sort of thing can reduce the amount of conditional logic in your templates, letting you use the same set of classes regardless of what state an input is in and letting the browser apply the right styles for you.

Tailwind 还包括适用于其他表单状态的变体,例如 :read-only:indeterminate:checked 等。

🌐 Tailwind also includes variants for other form states like :read-only, :indeterminate, :checked, and more.

查看 伪类参考 以获取可用伪类变体的完整列表。

🌐 See the pseudo-class reference for a complete list of available pseudo-class variants.

:has()

使用 has-* 变体根据其子元素的状态或内容来为元素设置样式:

🌐 Use the has-* variant to style an element based on the state or content of its descendants:

Payment method
<label  class="has-checked:bg-indigo-50 has-checked:text-indigo-900 has-checked:ring-indigo-200 dark:has-checked:bg-indigo-950 dark:has-checked:text-indigo-200 dark:has-checked:ring-indigo-900 ...">  <svg fill="currentColor">    <!-- ... -->  </svg>  Google Pay  <input type="radio" class="checked:border-indigo-500 ..." /></label>

你可以将 has-* 与伪类一起使用,例如 has-[:focus],以根据其子元素的状态来为元素设置样式。你也可以使用元素选择器,例如 has-[img]has-[a],以根据其子元素的内容来为元素设置样式。

🌐 You can use has-* with a pseudo-class, like has-[:focus], to style an element based on the state of its descendants. You can also use element selectors, like has-[img] or has-[a], to style an element based on the content of its descendants.

基于组的后代的样式(Styling based on the descendants of a group)

如果你需要根据父元素的子元素来为一个元素设置样式,你可以给父元素添加 group 类,并使用 group-has-* 变体来为目标元素设置样式:

🌐 If you need to style an element based on the descendants of a parent element, you can mark the parent with the group class and use the group-has-* variant to style the target element:

斯宾塞·夏普

产品设计师 在planeteria.tech

凯西·乔丹

很高兴能来到这里。

亚历克斯·里德

一名多学科设计师,致力于艺术与科技的交叉字段。

alex-reed.com

泰勒·贝利

推动像素。摆弄 div。

<div class="group ...">  <img src="..." />  <h4>Spencer Sharp</h4>  <svg class="hidden group-has-[a]:block ..."><!-- ... --></svg>  <p>Product Designer at <a href="...">planeteria.tech</a></p></div>

基于同级的后代的样式(Styling based on the descendants of a peer)

如果你需要根据兄弟元素的子元素来为某个元素设置样式,你可以给兄弟元素添加 peer 类,并使用 peer-has-* 变体来为目标元素设置样式:

🌐 If you need to style an element based on the descendants of a sibling element, you can mark the sibling with the peer class and use the peer-has-* variant to style the target element:

Today
<div>  <label class="peer ...">    <input type="checkbox" name="todo[1]" checked />    Create a to do list  </label>  <svg class="peer-has-checked:hidden ..."><!-- ... --></svg></div>

:not()

当条件不满足时,使用 not- 变体来设置元素样式。

🌐 Use the not- variant to style an element when a condition is not true.

当与其他伪类变体结合使用时,它尤其强大,例如将 not-focus:hover: 结合,只在元素未获得焦点时应用悬停样式:

🌐 It's particularly powerful when combined with other pseudo-class variants, for example combining not-focus: with hover: to only apply hover styles when an element is not focused:

试着专注于这个按钮,然后将鼠标悬停在上面

<button class="bg-indigo-600 hover:not-focus:bg-indigo-700">  <!-- ... --></button>

你也可以将 not- 变体与媒体查询变体如 forced-colorssupports 结合使用,以仅在用户环境中某些条件不满足时对元素进行样式设置:

🌐 You can also combine the not- variant with media query variants like forced-colors or supports to only style an element when something about the user's environment is not true:

<div class="not-supports-[display:grid]:flex">  <!-- ... --></div>

基于父状态的样式(Styling based on parent state)

当你需要根据某个 元素的状态来给元素添加样式时,请在父元素上标记 group 类,并使用类似 group-hovergroup-* 变体来为目标元素添加样式:

🌐 When you need to style an element based on the state of some parent element, mark the parent with the group class, and use group-* variants like group-hover to style the target element:

将鼠标悬停在卡片上以查看两个文本元素的颜色变化

<a href="#" class="group ...">  <div>    <svg class="stroke-sky-500 group-hover:stroke-white ..." fill="none" viewBox="0 0 24 24">      <!-- ... -->    </svg>    <h3 class="text-gray-900 group-hover:text-white ...">New project</h3>  </div>  <p class="text-gray-500 group-hover:text-white ...">Create a new project from a variety of starting templates.</p></a>

这个模式适用于每一个伪类变体,例如 group-focusgroup-active,甚至 group-odd

🌐 This pattern works with every pseudo-class variant, for example group-focus, group-active, or even group-odd.

区分嵌套组(Differentiating nested groups)

在嵌套分组时,你可以通过给特定的父组一个唯一的组名(使用 group/{name} 类),并在类中包含该名称(如 group-hover/{name})来基于特定父组的状态为元素设置样式:

🌐 When nesting groups, you can style something based on the state of a specific parent group by giving that parent a unique group name using a group/{name} class, and including that name in variants using classes like group-hover/{name}:

<ul role="list">  {#each people as person}    <li class="group/item ...">      <!-- ... -->      <a class="group/edit invisible group-hover/item:visible ..." href="tel:{person.phone}">        <span class="group-hover/edit:text-gray-700 ...">Call</span>        <svg class="group-hover/edit:translate-x-0.5 group-hover/edit:text-gray-500 ..."><!-- ... --></svg>      </a>    </li>  {/each}</ul>

组可以按照你喜欢的方式命名,并且不需要以任何方式进行配置 - 只需直接在标记中命名你的组,Tailwind 将自动生成必要的 CSS。

🌐 Groups can be named however you like and don’t need to be configured in any way — just name your groups directly in your markup and Tailwind will automatically generate the necessary CSS.

任意组(Arbitrary groups)

你可以通过在方括号中提供自己的选择器作为任意值来即时创建一次性的 group-* 变体:

🌐 You can create one-off group-* variants on the fly by providing your own selector as an arbitrary value between square brackets:

<div class="group is-published">  <div class="hidden group-[.is-published]:block">    Published  </div></div>

为了获得更多控制,你可以使用 & 字符来标记 .group 在最终选择器中相对于你传入的选择器应该出现在的位置:

🌐 For more control, you can use the & character to mark where .group should end up in the final selector relative to the selector you are passing in:

<div class="group">  <div class="group-[:nth-of-type(3)_&]:block">    <!-- ... -->  </div></div>

隐式组(Implicit groups)

in-* 变体的工作方式类似于 group,只是你不需要将 group 添加到父元素中:

🌐 The in-* variant works similarly to group except you don't need to add group to the parent element:

<div tabindex="0" class="group">  <div class="opacity-50 group-focus:opacity-100"><div tabindex="0">  <div class="opacity-50 in-focus:opacity-100">    <!-- ... -->  </div></div>

in-* 变体会对任意父级的状态变化作出响应,因此如果你想要更精细的控制,需要改用 group

🌐 The in-* variant responds to state changes in any parent, so if you want more fine-grained control you'll need to use group instead.

基于兄弟状态的样式(Styling based on sibling state)

当你需要根据兄弟元素的状态来设置元素的样式时,给兄弟元素添加 peer 类,并使用 peer-* 变体例如 peer-invalid 来设置目标元素的样式:

🌐 When you need to style an element based on the state of a sibling element, mark the sibling with the peer class, and use peer-* variants like peer-invalid to style the target element:

尝试使电子邮件地址有效,以查看警告是否消失

<form>  <label class="block">    <span class="...">Email</span>    <input type="email" class="peer ..." />    <p class="invisible peer-invalid:visible ...">Please provide a valid email address.</p>  </label></form>

这使得可以做各种很棒的操作,比如例如无需任何 JS 就实现浮动标签

🌐 This makes it possible to do all sorts of neat tricks, like floating labels for example without any JS.

这个模式适用于每个伪类变体,例如 peer-focuspeer-requiredpeer-disabled

🌐 This pattern works with every pseudo-class variant, for example peer-focus, peer-required, and peer-disabled.

需要注意的是,由于 CSS 中 subsequent-sibling combinator 的工作方式,peer 标记只能用于 前一个 兄弟元素:

🌐 It's important to note that the peer marker can only be used on previous siblings because of how the subsequent-sibling combinator works in CSS:

不起作用,只有前面的同级元素可以被标记为同级

<label>  <span class="peer-invalid:text-red-500 ...">Email</span>  <input type="email" class="peer ..." /></label>

区分同行(Differentiating peers)

使用多个 peer 时,你可以通过为某个 特定 的 peer 指定一个唯一名称(使用 peer/{name} 类),并在变体中使用像 peer-checked/{name} 这样的类包含该名称,从而根据该 peer 的状态来为某些元素设置样式:

🌐 When using multiple peers, you can style something on the state of a specific peer by giving that peer a unique name using a peer/{name} class, and including that name in variants using classes like peer-checked/{name}:

Published status
<fieldset>  <legend>Published status</legend>  <input id="draft" class="peer/draft" type="radio" name="status" checked />  <label for="draft" class="peer-checked/draft:text-sky-500">Draft</label>  <input id="published" class="peer/published" type="radio" name="status" />  <label for="published" class="peer-checked/published:text-sky-500">Published</label>  <div class="hidden peer-checked/draft:block">Drafts are only visible to administrators.</div>  <div class="hidden peer-checked/published:block">Your post will be publicly visible on your site.</div></fieldset>

对等点可以按照你喜欢的方式命名,并且不需要以任何方式进行配置 - 只需直接在标记中命名你的对等点,Tailwind 将自动生成必要的 CSS。

🌐 Peers can be named however you like and don’t need to be configured in any way — just name your peers directly in your markup and Tailwind will automatically generate the necessary CSS.

任意同行(Arbitrary peers)

你可以通过在方括号中提供自己的选择器作为任意值来即时创建一次性的 peer-* 变体:

🌐 You can create one-off peer-* variants on the fly by providing your own selector as an arbitrary value between square brackets:

<form>  <label for="email">Email:</label>  <input id="email" name="email" type="email" class="is-dirty peer" required />  <div class="peer-[.is-dirty]:peer-required:block hidden">This field is required.</div>  <!-- ... --></form>

为了获得更多控制,你可以使用 & 字符来标记 .peer 在最终选择器中相对于你传入的选择器应该出现在的位置:

🌐 For more control, you can use the & character to mark where .peer should end up in the final selector relative to the selector you are passing in:

<div>  <input type="text" class="peer" />  <div class="hidden peer-[:nth-of-type(3)_&]:block">    <!-- ... -->  </div></div>

伪元素(Pseudo-elements)

::before 和 ::after(::before and ::after)

使用 beforeafter 变体为 ::before::after 伪元素设置样式:

🌐 Style the ::before and ::after pseudo-elements using the before and after variants:

<label>  <span class="text-gray-700 after:ml-0.5 after:text-red-500 after:content-['*'] ...">Email</span>  <input type="email" name="email" class="..." placeholder="you@example.com" /></label>

在使用这些变体时,Tailwind 会默认自动添加 content: '',所以除非你想使用不同的值,否则不必手动指定:

🌐 When using these variants, Tailwind will automatically add content: '' by default so you don't have to specify it unless you want a different value:

When you look annoyed all the time, people think that you're busy.
<blockquote class="text-center text-2xl font-semibold text-gray-900 italic dark:text-white">  When you look  <span class="relative inline-block before:absolute before:-inset-1 before:block before:-skew-y-3 before:bg-pink-500">    <span class="relative text-white dark:text-gray-950">annoyed</span>  </span>  all the time, people think that you're busy.</blockquote>

值得注意的是,在大多数 Tailwind 项目中,你其实并不需要 ::before::after 伪元素 —— 通常直接使用真实的 HTML 元素要更简单。

🌐 It's worth noting that you don't really need ::before and ::after pseudo-elements for most things in Tailwind projects — it's usually simpler to just use a real HTML element.

例如,下面是上面相同的设计,但使用 <span> 而不是 ::before 伪元素,这样更容易阅读,而且代码实际上更少:

🌐 For example, here's the same design from above but using a <span> instead of the ::before pseudo-element, which is a little easier to read and is actually less code:

<blockquote class="text-center text-2xl font-semibold text-gray-900 italic">  When you look  <span class="relative">    <span class="absolute -inset-1 block -skew-y-3 bg-pink-500" aria-hidden="true"></span>    <span class="relative text-white">annoyed</span>  </span>  all the time, people think that you're busy.</blockquote>

beforeafter 留作在伪元素的内容实际上不在 DOM 中且用户无法选择的情况下使用。

🌐 Save before and after for situations where it's important that the content of the pseudo-element is not actually in the DOM and can't be selected by the user.

::placeholder

使用 placeholder 变体为任何输入框或文本区域的占位符文本设置样式:

🌐 Style the placeholder text of any input or textarea using the placeholder variant:

<input  class="placeholder:text-gray-500 placeholder:italic ..."  placeholder="Search for anything..."  type="text"  name="search"/>

::file

使用 file 变体为文件输入的按钮设置样式:

🌐 Style the button in file inputs using the file variant:

Current profile photo
<input  type="file"  class="file:mr-4 file:rounded-full file:border-0 file:bg-violet-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-violet-700 hover:file:bg-violet-100 dark:file:bg-violet-600 dark:file:text-violet-100 dark:hover:file:bg-violet-500 ..."/>

::marker

使用 marker 变体为列表中的计数器或项目符号设置样式:

🌐 Style the counters or bullets in lists using the marker variant:

Ingredients

  • 5 cups chopped Porcini mushrooms
  • 1/2 cup of olive oil
  • 3lb of celery
<ul role="list" class="list-disc marker:text-sky-400 ...">  <li>5 cups chopped Porcini mushrooms</li>  <li>1/2 cup of olive oil</li>  <li>3lb of celery</li></ul>

我们把 marker 变体设计为可继承的,所以虽然你可以直接在 <li> 元素上使用它,也可以在父元素上使用它,以避免重复操作。

🌐 We've designed the marker variant to be inheritable, so although you can use it directly on an <li> element, you can also use it on a parent to avoid repeating yourself.

::selection

使用 selection 变体为活动文本选择设置样式:

🌐 Style the active text selection using the selection variant:

试着用鼠标选择这段文字

So I started to walk into the water. I won't lie to you boys, I was terrified. But I pressed on, and as I made my way past the breakers a strange calm came over me. I don't know if it was divine intervention or the kinship of all living things but I tell you Jerry at that moment, I was a marine biologist.

<div class="selection:bg-fuchsia-300 selection:text-fuchsia-900">  <p>    So I started to walk into the water. I won't lie to you boys, I was terrified. But I pressed on, and as I made my    way past the breakers a strange calm came over me. I don't know if it was divine intervention or the kinship of all    living things but I tell you Jerry at that moment, I <em>was</em> a marine biologist.  </p></div>

我们将 selection 变体设计为可继承,因此你可以将它添加到树中的任何位置,它将应用于所有子元素。

🌐 We've designed the selection variant to be inheritable, so you can add it anywhere in the tree and it will be applied to all descendant elements.

这使得设置选择颜色以在整个站点上匹配你的品牌变得容易:

🌐 This makes it easy to set the selection color to match your brand across your entire site:

<html>  <head>    <!-- ... -->  </head>  <body class="selection:bg-pink-300">    <!-- ... -->  </body></html>

::first-line 和 ::first-letter(::first-line and ::first-letter)

使用 first-line 变体为内容块的第一行设置样式,并使用 first-letter 变体为首字母设置样式:

🌐 Style the first line in a block of content using the first-line variant, and the first letter using the first-letter variant:

Well, let me tell you something, funny boy. Y'know that little stamp, the one that says "New York Public Library"? Well that may not mean anything to you, but that means a lot to me. One whole hell of a lot.

Sure, go ahead, laugh if you want to. I've seen your type before: Flashy, making the scene, flaunting convention. Yeah, I know what you're thinking. What's this guy making such a big stink about old library books? Well, let me give you a hint, junior.

<div class="text-gray-700">  <p    class="first-letter:float-left first-letter:mr-3 first-letter:text-7xl first-letter:font-bold first-letter:text-gray-900 first-line:tracking-widest first-line:uppercase"  >    Well, let me tell you something, funny boy. Y'know that little stamp, the one that says "New York Public Library"?  </p>  <p class="mt-6">Well that may not mean anything to you, but that means a lot to me. One whole hell of a lot.</p></div>

::backdrop

使用 backdrop 变体为 原生 <dialog> 元素 设置背景样式:

🌐 Style the backdrop of a native <dialog> element using the backdrop variant:

<dialog class="backdrop:bg-gray-50">  <form method="dialog">    <!-- ... -->  </form></dialog>

如果你在项目中使用原生 <dialog> 元素,你可能也想了解如何使用 open 变体来 为打开/关闭状态设置样式

🌐 If you're using native <dialog> elements in your project, you may also want to read about styling open/closed states using the open variant.

媒体和特性查询(Media and feature queries)

响应式断点(Responsive breakpoints)

要在特定断点为元素设置样式,请使用响应式变体,例如 mdlg

🌐 To style an element at a specific breakpoint, use responsive variants like md and lg.

例如,这将在移动设备上渲染 3 列网格,在中等宽度屏幕上渲染 4 列网格,在大宽度屏幕上渲染 6 列网格:

🌐 For example, this will render a 3-column grid on mobile, a 4-column grid on medium-width screens, and a 6-column grid on large-width screens:

<div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6">  <!-- ... --></div>

要根据父元素的宽度而不是视口来设置元素样式,可以使用像 @md@lg 这样的变体:

🌐 To style an element based on the width of a parent element instead of the viewport, use variants like @md and @lg:

<div class="@container">  <div class="flex flex-col @md:flex-row">    <!-- ... -->  </div></div>

查看 响应式设计 文档,深入了解这些功能的工作原理。

🌐 Check out the Responsive design documentation for an in-depth look at how these features work.

prefers-color-scheme

prefers-color-scheme 媒体查询可以告诉你用户偏好使用浅色主题还是深色主题,通常在操作系统级别进行配置。

🌐 The prefers-color-scheme media query tells you whether the user prefers a light theme or dark theme, and is usually configured at the operating system level.

使用没有变体的工具类来针对浅色模式,使用 dark 变体来为夜间模式提供覆盖:

🌐 Use utilities with no variant to target light mode, and use the dark variant to provide overrides for dark mode:

Light mode

倒着写

零重力笔可以在任何方向书写,包括倒着写。它甚至可以在外太空使用。

暗黑模式

可以倒着书写

零重力笔可以在任何方向书写,包括倒着书写。它甚至可以在外太空使用。

<div class="bg-white dark:bg-gray-900 ...">  <!-- ... -->  <h3 class="text-gray-900 dark:text-white ...">Writes upside-down</h3>  <p class="text-gray-500 dark:text-gray-400 ...">    The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space.  </p></div>

查看 暗黑模式 文档,深入了解此功能的工作原理。

🌐 Check out the Dark Mode documentation for an in-depth look at how this feature works.

prefers-reduced-motion

prefers-reduced-motion 媒体查询告诉你用户是否请求你尽量减少非必要的动画效果。

🌐 The prefers-reduced-motion media query tells you if the user has requested that you minimize non-essential motion.

当用户请求减少动画时,使用 motion-reduce 变体有条件地添加样式:

🌐 Use the motion-reduce variant to conditionally add styles when the user has requested reduced motion:

尝试在你的开发者工具中模拟 `prefers-reduced-motion: reduce` 来隐藏加载动画

<button type="button" class="bg-indigo-500 ..." disabled>  <svg class="animate-spin motion-reduce:hidden ..." viewBox="0 0 24 24"><!-- ... --></svg>  Processing...</button>

Tailwind 还包括一个 motion-safe 变体,它只有在用户没有请求减少动画效果时才会添加样式。当使用 motion-reduce 辅助工具意味着需要“撤销”大量样式时,这会很有用:

🌐 Tailwind also includes a motion-safe variant that only adds styles when the user has not requested reduced motion. This can be useful when using the motion-reduce helper would mean having to "undo" a lot of styles:

<!-- Using `motion-reduce` can mean lots of "undoing" styles --><button class="transition hover:-translate-y-0.5 motion-reduce:transition-none motion-reduce:hover:translate-y-0 ...">  Save changes</button><!-- Using `motion-safe` is less code in these situations --><button class="motion-safe:transition motion-safe:hover:-translate-x-0.5 ...">Save changes</button>

prefers-contrast

prefers-contrast 媒体查询可以告诉你用户是否请求了更多或更少的对比度。

🌐 The prefers-contrast media query tells you if the user has requested more or less contrast.

使用 contrast-more 变体在用户请求更高对比度时有条件地添加样式:

🌐 Use the contrast-more variant to conditionally add styles when the user has requested more contrast:

尝试在开发者工具中模拟 `prefers-contrast: more` 来查看变化

We need this to steal your identity.

<label class="block">  <span class="block text-sm font-medium text-gray-700">Social Security Number</span>  <input    class="border-gray-200 placeholder-gray-400 contrast-more:border-gray-400 contrast-more:placeholder-gray-500 ..."  />  <p class="text-gray-600 opacity-10 contrast-more:opacity-100 ...">We need this to steal your identity.</p></label>

Tailwind 还包括一个 contrast-less 变体,你可以在用户请求较低对比度时有条件地添加样式。

🌐 Tailwind also includes a contrast-less variant you can use to conditionally add styles when the user has requested less contrast.

forced-colors

forced-colors 媒体查询用于指示用户是否正在使用强制颜色模式。这些模式会用用户定义的调色板覆盖你网站的颜色,包括文本、背景、链接和按钮。

🌐 The forced-colors media query indicates if the user is using a forced colors mode. These modes override your site's colors with a user defined palette for text, backgrounds, links and buttons.

使用 forced-colors 变体在用户启用强制颜色模式时有条件地添加样式:

🌐 Use the forced-colors variant to conditionally add styles when the user has enabled a forced color mode:

尝试在开发者工具中模拟 `forced-colors: active` 来查看变化

Choose a theme:
<label>  <input type="radio" class="appearance-none forced-colors:appearance-auto" />  <p class="hidden forced-colors:block">Cyan</p>  <div class="bg-cyan-200 forced-colors:hidden ..."></div>  <div class="bg-cyan-500 forced-colors:hidden ..."></div></label>

当用户未使用强制颜色模式时,使用 not-forced-colors 变体来应用样式:

🌐 Use the not-forced-colors variant to apply styles based when the user is not using a forced colors mode:

<div class="not-forced-colors:appearance-none ...">  <!-- ... --></div>

Tailwind 还包括一个 强制颜色调整 工具,允许选择启用或禁用强制颜色。

🌐 Tailwind also includes a forced color adjust utilities to opt in and out of forced colors.

inverted-colors

使用 inverted-colors 变体在用户启用反色配色方案时有条件地添加样式:

🌐 Use the inverted-colors variant to conditionally add styles when the user has enabled an inverted color scheme:

<div class="shadow-xl inverted-colors:shadow-none ...">  <!-- ... --></div>

指针和任意指针(pointer and any-pointer)

pointer 媒体查询可以告诉你用户是否有主要的指点设备(如鼠标),以及该指点设备的精确度。

🌐 The pointer media query tells you whether the user has a primary pointing device, like a mouse, and the accuracy of that pointing device.

使用 pointer-fine 变体以针对精确的指点设备,如鼠标或触控板,或使用 pointer-coarse 变体以针对精度较低的指点设备,如触摸屏,这在触摸设备上提供更大的点击目标时非常有用:

🌐 Use the pointer-fine variant to target an accurate pointing device, like a mouse or trackpad, or the pointer-coarse variant to target a less accurate pointing device, like a touchscreen, which can be useful for providing larger click targets on touch devices:

尝试在开发者工具中模拟触摸设备以查看更改

<fieldset aria-label="Choose a memory option">  <div class="flex items-center justify-between">    <div>RAM</div>    <a href="#"> See performance specs </a>  </div>  <div class="mt-4 grid grid-cols-6 gap-2 pointer-coarse:mt-6 pointer-coarse:grid-cols-3 pointer-coarse:gap-4">    <label class="p-2 pointer-coarse:p-4 ...">      <input type="radio" name="memory-option" value="4 GB" className="sr-only" />      <span>4 GB</span>    </label>    <!-- ... -->  </div></fieldset>

pointer 只针对主要的指向设备,而 any-pointer 用于针对可能可用的任何指向设备。如果至少有一个已连接的指向设备符合条件,请使用 any-pointer-fineany-pointer-coarse 变体来提供不同的样式。

🌐 While pointeronly targets the primary pointing device, any-pointer is used to target any of the pointing devices that might be available. Use the any-pointer-fine and any-pointer-coarse variants to provide different styles if at least one connected pointing device meets the criteria.

你可以使用 pointer-noneany-pointer-none 来针对缺少指点设备的情况。

🌐 You can use pointer-none and any-pointer-none to target the absence of a pointing device.

orientation

使用 portraitlandscape 变体在视口处于特定方向时有条件地添加样式:

🌐 Use the portrait and landscape variants to conditionally add styles when the viewport is in a specific orientation:

<div>  <div class="portrait:hidden">    <!-- ... -->  </div>  <div class="landscape:hidden">    <p>This experience is designed to be viewed in landscape. Please rotate your device to view the site.</p>  </div></div>

scripting

使用 noscript 变体根据用户是否启用了脚本(如 JavaScript)有条件地添加样式:

🌐 Use the noscript variant to conditionally add styles based on whether the user has scripting, such as JavaScript, enabled:

<div class="hidden noscript:block">  <p>This experience requires JavaScript to function. Please enable JavaScript in your browser settings.</p></div>

print

使用 print 变体有条件地添加仅在打印文档时生效的样式:

🌐 Use the print variant to conditionally add styles that only apply when the document is being printed:

<div>  <article class="print:hidden">    <h1>My Secret Pizza Recipe</h1>    <p>This recipe is a secret, and must not be shared with anyone</p>    <!-- ... -->  </article>  <div class="hidden print:block">Are you seriously trying to print this? It's secret!</div></div>

@supports

使用 supports-[...] 变体根据用户浏览器是否支持某个功能来设置样式:

🌐 Use the supports-[...] variant to style things based on whether a certain feature is supported in the user's browser:

<div class="flex supports-[display:grid]:grid ...">  <!-- ... --></div>

在底层,supports-[...] 变体会生成 @supports rules,并且可以在方括号中使用 @supports (...) 的任何内容,比如属性/值对,甚至可以使用 andor 的表达式。

🌐 Under the hood the supports-[...] variant generates @supports rules and takes anything you’d use with @supports (...) between the square brackets, like a property/value pair, and even expressions using and and or.

为了简洁起见,如果你只需要检查一个属性是否被支持(而不是一个特定的值),你可以只指定属性名称:

🌐 For terseness, if you only need to check if a property is supported (and not a specific value), you can just specify the property name:

<div class="bg-black/75 supports-backdrop-filter:bg-black/25 supports-backdrop-filter:backdrop-blur ...">  <!-- ... --></div>

使用 not-supports-[...] 变体根据用户浏览器是否不支持某个功能来设置样式:

🌐 Use the not-supports-[...] variant to style things based on whether a certain feature is not supported in the user's browser:

<div class="not-supports-[display:grid]:flex">  <!-- ... --></div>

你可以通过在 supports-* 命名空间中创建一个新变体,为项目中使用的常见 @supports 规则配置快捷方式:

🌐 You can configure shortcuts for common @supports rules you're using in your project by creating a new variant in the supports-* namespace:

@custom-variant supports-grid {  @supports (display: grid) {    @slot;  }}

然后你可以在你的项目中使用这些自定义的 supports-* 变体:

🌐 You can then use these custom supports-* variants in your project:

<div class="supports-grid:grid">  <!-- ... --></div>

@starting-style

使用 starting 变体来设置元素在首次渲染到 DOM 时或从 display: none 变为可见时的外观:

🌐 Use the starting variant to set the appearance of an element when it is first rendered in the DOM, or transitions from display: none to visible:

<div>  <button popovertarget="my-popover">Check for updates</button>  <div popover id="my-popover" class="opacity-0 starting:open:opacity-0 ...">    <!-- ... -->  </div></div>

属性选择器(Attribute selectors)

ARIA 状态(ARIA states)

使用 aria-* 变体根据 ARIA 属性 有条件地设置样式。

🌐 Use the aria-* variant to conditionally style things based on ARIA attributes.

例如,要在 aria-checked 属性设置为 true 时应用 bg-sky-700 类,可以使用 aria-checked:bg-sky-700 类:

🌐 For example, to apply the bg-sky-700 class when the aria-checked attribute is set to true, use the aria-checked:bg-sky-700 class:

<div aria-checked="true" class="bg-gray-600 aria-checked:bg-sky-700">  <!-- ... --></div>

默认情况下,我们已包含最常见布尔 ARIA 属性的变体:

🌐 By default we've included variants for the most common boolean ARIA attributes:

VariantCSS
aria-busy&[aria-busy="true"]
aria-checked&[aria-checked="true"]
aria-disabled&[aria-disabled="true"]
aria-expanded&[aria-expanded="true"]
aria-hidden&[aria-hidden="true"]
aria-pressed&[aria-pressed="true"]
aria-readonly&[aria-readonly="true"]
aria-required&[aria-required="true"]
aria-selected&[aria-selected="true"]

你可以通过创建新变体来自定义可用的 aria-* 变体:

🌐 You can customize which aria-* variants are available by creating a new variant:

@custom-variant aria-asc (&[aria-sort="ascending"]);@custom-variant aria-desc (&[aria-sort="descending"]);

如果你需要使用一个一次性的 aria 变体,而它不适合包含在你的项目中,或者对于需要特定值的更复杂的 ARIA 属性,可以使用方括号即时生成一个任意值的属性:

🌐 If you need to use a one-off aria variant that doesn’t make sense to include in your project, or for more complex ARIA attributes that take specific values, use square brackets to generate a property on the fly using any arbitrary value:

Invoice #ClientAmount
#100Pendant Publishing$2,000.00
#101Kruger Industrial Smoothing$545.00
#102J. Peterman$10,000.25
<table>  <thead>    <tr>      <th        aria-sort="ascending"        class="aria-[sort=ascending]:bg-[url('/img/down-arrow.svg')] aria-[sort=descending]:bg-[url('/img/up-arrow.svg')]"      >        Invoice #      </th>      <!-- ... -->    </tr>  </thead>  <!-- ... --></table>

ARIA 状态变体也可以使用 group-aria-*peer-aria-* 变体来针对父元素和兄弟元素:

🌐 ARIA state variants can also target parent and sibling elements using the group-aria-* and peer-aria-* variants:

<table>  <thead>    <tr>    <th aria-sort="ascending" class="group">      Invoice #      <svg class="group-aria-[sort=ascending]:rotate-0 group-aria-[sort=descending]:rotate-180"><!-- ... --></svg>    </th>    <!-- ... -->    </tr>  </thead>  <!-- ... --></table>

数据属性(Data attributes)

使用 data-* 变体根据 数据属性 有条件地应用样式。

🌐 Use the data-* variant to conditionally apply styles based on data attributes.

要检查数据属性是否存在(而不是特定值),你只需指定属性名称即可:

🌐 To check if a data attribute exists (and not a specific value), you can just specify the attribute name:

<!-- Will apply --><div data-active class="border border-gray-300 data-active:border-purple-500">  <!-- ... --></div><!-- Will not apply --><div class="border border-gray-300 data-active:border-purple-500">  <!-- ... --></div>

如果你需要检查特定值,则可以使用任意值:

🌐 If you need to check for a specific value you may use an arbitrary value:

<!-- Will apply --><div data-size="large" class="data-[size=large]:p-8">  <!-- ... --></div><!-- Will not apply --><div data-size="medium" class="data-[size=large]:p-8">  <!-- ... --></div>

或者,你可以通过在 data-* 命名空间中创建一个新变体,为你在项目中使用的常用数据属性配置快捷方式:

🌐 Alternatively, you can configure shortcuts for common data attributes you're using in your project by creating a new variant in the data-* namespace:

app.css
@import "tailwindcss";@custom-variant data-checked (&[data-ui~="checked"]);

然后你可以在项目中使用这些自定义的 data-* 变体:

🌐 You can then use these custom data-* variants in your project:

<div data-ui="checked active" class="data-checked:underline">  <!-- ... --></div>

RTL 支持(RTL support)

在构建多方向布局时,使用 rtlltr 变体分别在从右到左和从左到右模式下有条件地添加样式:

🌐 Use the rtl and ltr variants to conditionally add styles in right-to-left and left-to-right modes respectively when building multi-directional layouts:

Left-to-right

Tom Cook

Director of Operations

Right-to-left

تامر كرم

الرئيس التنفيذي

<div class="group flex items-center">  <img class="h-12 w-12 shrink-0 rounded-full" src="..." alt="" />  <div class="ltr:ml-3 rtl:mr-3">    <p class="text-gray-700 group-hover:text-gray-900 ...">...</p>    <p class="text-gray-500 group-hover:text-gray-700 ...">...</p>  </div></div>

请记住,这些变体只有在你正在构建需要支持左右双向布局的网站时才有用。如果你构建的网站只需要支持单一方向,则不需要这些变体——只需应用适合你内容的样式即可。

🌐 Remember, these variants are only useful if you are building a site that needs to support both left-to-right and right-to-left layouts. If you're building a site that only needs to support a single direction, you don't need these variants — just apply the styles that make sense for your content.

打开/关闭状态(Open/closed state)

使用 open 变体,当 <details><dialog> 元素处于打开状态时有条件地添加样式:

🌐 Use the open variant to conditionally add styles when a <details> or <dialog> element is in an open state:

尝试切换展开项,看看样式如何变化

Why do they call it Ovaltine?

The mug is round. The jar is round. They should call it Roundtine.

<details class="border border-transparent open:border-black/10 open:bg-gray-100 ..." open>  <summary class="text-sm leading-6 font-semibold text-gray-900 select-none">Why do they call it Ovaltine?</summary>  <div class="mt-3 text-sm leading-6 text-gray-600">    <p>The mug is round. The jar is round. They should call it Roundtine.</p>  </div></details>

这个变体也针对弹出框的 :popover-open 伪类:

🌐 This variant also targets the :popover-open pseudo-class for popovers:

<div>  <button popovertarget="my-popover">Open Popover</button>  <div popover id="my-popover" class="opacity-0 open:opacity-100 ...">    <!-- ... -->  </div></div>

设置惰性元素的样式(Styling inert elements)

inert 变体允许你为带有 inert 属性的元素设置样式:

🌐 The inert variant lets you style elements marked with the inert attribute:

Notification preferences

Get notified when someones posts a comment on a post.

Get notified when someones mentions you.

<form>  <legend>Notification preferences</legend>  <fieldset>    <input type="radio" />    <label> Custom </label>    <fieldset inert class="inert:opacity-50">      <!-- ... -->    </fieldset>    <input type="radio" />    <label> Everything </label>  </fieldset></form>

这对于添加视觉提示非常有用,可以清楚地表明内容部分不是交互式的。

🌐 This is useful for adding visual cues that make it clear that sections of content aren't interactive.

子选择器(Child selectors)

设置直接子级的样式(Styling direct children)

虽然通常最好将实用类直接放在子元素上,但在需要为你无法控制的直接子元素设置样式的情况下,你可以使用 * 变体:

🌐 While it's generally preferable to put utility classes directly on child elements, you can use the * variant in situations where you need to style direct children that you don’t have control over:

Categories

Sales
Marketing
SEO
Analytics
Design
Strategy
Security
Growth
Mobile
UX/UI
<div>  <h2>Categories<h2>  <ul class="*:rounded-full *:border *:border-sky-100 *:bg-sky-50 *:px-2 *:py-0.5 dark:text-sky-300 dark:*:border-sky-500/15 dark:*:bg-sky-500/10 ...">    <li>Sales</li>    <li>Marketing</li>    <li>SEO</li>    <!-- ... -->  </ul></div>

需要注意的是,直接在子规则本身上使用实用程序覆盖样式是行不通的,因为子规则是在常规规则之后生成的,并且它们具有相同的特殊性:

🌐 It's important to note that overriding a style with a utility directly on the child itself won't work since children rules are generated after the regular ones and they have the same specificity:

行不通,子级无法覆盖父元素赋予它们的样式。

<ul class="*:bg-sky-50 ...">  <li class="bg-red-50 ...">Sales</li>  <li>Marketing</li>  <li>SEO</li>  <!-- ... --></ul>

设置所有后代的样式(Styling all descendants)

* 一样,** 变体可以用于为一个元素的子元素设置样式。主要的区别是 ** 会将样式应用于所有后代,而不仅仅是直接子元素。当你将它与另一个变体结合使用以缩小所选对象时,这尤其有用:

🌐 Like *, the ** variant can be used to style children of an element. The main difference is that ** will apply styles to all descendants, not just the direct children. This is especially useful when you combine it with another variant for narrowing the thing you're selecting:

<ul class="**:data-avatar:size-12 **:data-avatar:rounded-full ...">  {#each items as item}    <li>      <img src={item.src} data-avatar />      <p>{item.name}</p>    </li>  {/each}</ul>

自定义变体(Custom variants)

使用任意变体(Using arbitrary variants)

就像 任意值 允许你在工具类中使用自定义值一样,任意变体允许你直接在 HTML 中编写自定义选择器变体。

🌐 Just like arbitrary values let you use custom values with your utility classes, arbitrary variants let you write custom selector variants directly in your HTML.

任意变体只是表示选择器的格式字符串,使用方括号括起来。例如,这个任意变体在元素具有 is-dragging 类时,将光标更改为 grabbing

🌐 Arbitrary variants are just format strings that represent the selector, wrapped in square brackets. For example, this arbitrary variant changes the cursor to grabbing when the element has the is-dragging class:

<ul role="list">  {#each items as item}    <li class="[&.is-dragging]:cursor-grabbing">{item}</li>  {/each}</ul>

任意变体可以与内置变体或彼此堆叠,就像 Tailwind 中的其他变体一样:

🌐 Arbitrary variants can be stacked with built-in variants or with each other, just like the rest of the variants in Tailwind:

<ul role="list">  {#each items as item}    <li class="[&.is-dragging]:active:cursor-grabbing">{item}</li>  {/each}</ul>

如果你的选择器中需要空格,可以使用下划线。例如,这个任意变体会选择你已添加类的元素内的所有 p 元素:

🌐 If you need spaces in your selector, you can use an underscore. For example, this arbitrary variant selects all p elements within the element where you've added the class:

<div class="[&_p]:mt-4">  <p>Lorem ipsum...</p>  <ul>    <li>      <p>Lorem ipsum...</p>    </li>    <!-- ... -->  </ul></div>

你也可以在任意变体中使用像 @media@supports 这样的 at 规则:

🌐 You can also use at-rules like @media or @supports in arbitrary variants:

<div class="flex [@supports(display:grid)]:grid">  <!-- ... --></div>

使用 at-rule 自定义变体时,不需要 & 占位符,就像在使用预处理器进行嵌套时一样。

🌐 With at-rule custom variants the & placeholder isn't necessary, just like when nesting with a preprocessor.

注册自定义变体(Registering a custom variant)

如果你发现自己在项目中多次使用相同的任意变体,那么使用 @custom-variant 指令创建自定义变体可能更为合适:

🌐 If you find yourself using the same arbitrary variant multiple times in your project, it might be worth creating a custom variant using the @custom-variant directive:

@custom-variant theme-midnight (&:where([data-theme="midnight"] *));

现在你可以在你的 HTML 中使用 theme-midnight:<utility> 变体:

🌐 Now you can use the theme-midnight:<utility> variant in your HTML:

<html data-theme="midnight">  <button class="theme-midnight:bg-black ..."></button></html>

了解有关在添加自定义变体文档中添加自定义变体的更多信息。

🌐 Learn more about adding custom variants in the adding custom variants documentation.

附录(Appendix)

快速参考(Quick reference)

默认情况下,Tailwind 中包含的每个变体的快速参考表。

🌐 A quick reference table of every single variant included in Tailwind by default.

VariantCSS
hover@media (hover: hover) { &:hover }
focus&:focus
focus-within&:focus-within
focus-visible&:focus-visible
active&:active
visited&:visited
target&:target
*:is(& > *)
**:is(& *)
has-[...]&:has(...)
group-[...]&:is(:where(.group)... *)
peer-[...]&:is(:where(.peer)... ~ *)
in-[...]:where(...) &
not-[...]&:not(...)
inert&:is([inert], [inert] *)
first&:first-child
last&:last-child
only&:only-child
odd&:nth-child(odd)
even&:nth-child(even)
first-of-type&:first-of-type
last-of-type&:last-of-type
only-of-type&:only-of-type
nth-[...]&:nth-child(...)
nth-last-[...]&:nth-last-child(...)
nth-of-type-[...]&:nth-of-type(...)
nth-last-of-type-[...]&:nth-last-of-type(...)
empty&:empty
disabled&:disabled
enabled&:enabled
checked&:checked
indeterminate&:indeterminate
default&:default
optional&:optional
required&:required
valid&:valid
invalid&:invalid
user-valid&:user-valid
user-invalid&:user-invalid
in-range&:in-range
out-of-range&:out-of-range
placeholder-shown&:placeholder-shown
details-content&:details-content
autofill&:autofill
read-only&:read-only
before&::before
after&::after
first-letter&::first-letter
first-line&::first-line
marker&::marker, & *::marker
selection&::selection
file&::file-selector-button
backdrop&::backdrop
placeholder&::placeholder
sm@media (width >= 40rem)
md@media (width >= 48rem)
lg@media (width >= 64rem)
xl@media (width >= 80rem)
2xl@media (width >= 96rem)
min-[...]@media (width >= ...)
max-sm@media (width < 40rem)
max-md@media (width < 48rem)
max-lg@media (width < 64rem)
max-xl@media (width < 80rem)
max-2xl@media (width < 96rem)
max-[...]@media (width < ...)
@3xs@container (width >= 16rem)
@2xs@container (width >= 18rem)
@xs@container (width >= 20rem)
@sm@container (width >= 24rem)
@md@container (width >= 28rem)
@lg@container (width >= 32rem)
@xl@container (width >= 36rem)
@2xl@container (width >= 42rem)
@3xl@container (width >= 48rem)
@4xl@container (width >= 56rem)
@5xl@container (width >= 64rem)
@6xl@container (width >= 72rem)
@7xl@container (width >= 80rem)
@min-[...]@container (width >= ...)
@max-3xs@container (width < 16rem)
@max-2xs@container (width < 18rem)
@max-xs@container (width < 20rem)
@max-sm@container (width < 24rem)
@max-md@container (width < 28rem)
@max-lg@container (width < 32rem)
@max-xl@container (width < 36rem)
@max-2xl@container (width < 42rem)
@max-3xl@container (width < 48rem)
@max-4xl@container (width < 56rem)
@max-5xl@container (width < 64rem)
@max-6xl@container (width < 72rem)
@max-7xl@container (width < 80rem)
@max-[...]@container (width < ...)
dark@media (prefers-color-scheme: dark)
motion-safe@media (prefers-reduced-motion: no-preference)
motion-reduce@media (prefers-reduced-motion: reduce)
contrast-more@media (prefers-contrast: more)
contrast-less@media (prefers-contrast: less)
forced-colors@media (forced-colors: active)
inverted-colors@media (inverted-colors: inverted)
pointer-fine@media (pointer: fine)
pointer-coarse@media (pointer: coarse)
pointer-none@media (pointer: none)
any-pointer-fine@media (any-pointer: fine)
any-pointer-coarse@media (any-pointer: coarse)
any-pointer-none@media (any-pointer: none)
portrait@media (orientation: portrait)
landscape@media (orientation: landscape)
noscript@media (scripting: none)
print@media print
supports-[]@supports ()
aria-busy&[aria-busy="true"]
aria-checked&[aria-checked="true"]
aria-disabled&[aria-disabled="true"]
aria-expanded&[aria-expanded="true"]
aria-hidden&[aria-hidden="true"]
aria-pressed&[aria-pressed="true"]
aria-readonly&[aria-readonly="true"]
aria-required&[aria-required="true"]
aria-selected&[aria-selected="true"]
aria-[]&[aria-]
data-[]&[data-]
rtl&:where(:dir(rtl), [dir="rtl"], [dir="rtl"] *)
ltr&:where(:dir(ltr), [dir="ltr"], [dir="ltr"] *)
open&:is([open], :popover-open, :open)
starting@starting-style

伪类参考(Pseudo-class reference)

这是一个包含 Tailwind 中所有伪类变体示例的综合列表,用于补充本指南开头的 伪类文档

🌐 This is a comprehensive list of examples for all the pseudo-class variants included in Tailwind to complement the pseudo-classes documentation at the beginning of this guide.

:hover

使用 hover 变体在用户将鼠标悬停在元素上时设置样式:

🌐 Style an element when the user hovers over it with the mouse cursor using the hover variant:

<div class="bg-black hover:bg-white ...">  <!-- ... --></div>

:focus

当元素获得焦点时,使用 focus 变体来设置样式:

🌐 Style an element when it has focus using the focus variant:

<input class="border-gray-300 focus:border-blue-400 ..." />

:focus-within

当元素或其某个子元素获得焦点时,使用 focus-within 变体来设置样式:

🌐 Style an element when it or one of its descendants has focus using the focus-within variant:

<div class="focus-within:shadow-lg ...">  <input type="text" /></div>

:focus-visible

使用 focus-visible 变体在元素通过键盘获得焦点时为其设置样式:

🌐 Style an element when it has been focused using the keyboard using the focus-visible variant:

<button class="focus-visible:outline-2 ...">Submit</button>

:active

在按下元素时使用 active 变体设置样式:

🌐 Style an element when it is being pressed using the active variant:

<button class="bg-blue-500 active:bg-blue-600 ...">Submit</button>

:visited

使用 visited 变体为已访问的链接设置样式:

🌐 Style a link when it has already been visited using the visited variant:

<a href="https://seinfeldquotes.com" class="text-blue-600 visited:text-purple-600 ..."> Inspiration </a>

:target

如果元素的 ID 与当前 URL 片段匹配,则使用 target 变体来设置样式:

🌐 Style an element if its ID matches the current URL fragment using the target variant:

<div id="about" class="target:shadow-lg ...">  <!-- ... --></div>

:first-child

如果一个元素是第一个子元素,使用 first 变体来设置样式:

🌐 Style an element if it's the first child using the first variant:

<ul>  {#each people as person}    <li class="py-4 first:pt-0 ...">      <!-- ... -->    </li>  {/each}</ul>

:last-child

如果一个元素是最后一个子元素,使用 last 变体来设置样式:

🌐 Style an element if it's the last child using the last variant:

<ul>  {#each people as person}    <li class="py-4 last:pb-0 ...">      <!-- ... -->    </li>  {/each}</ul>

:only-child

如果一个元素是唯一的子元素,使用 only 变体来设置样式:

🌐 Style an element if it's the only child using the only variant:

<ul>  {#each people as person}    <li class="py-4 only:py-0 ...">      <!-- ... -->    </li>  {/each}</ul>

:nth-child(odd)

如果一个元素是奇数编号的子元素,可以使用 odd 变体来设置样式:

🌐 Style an element if it's an oddly numbered child using the odd variant:

<table>  {#each people as person}    <tr class="bg-white odd:bg-gray-100 ...">      <!-- ... -->    </tr>  {/each}</table>

:nth-child(even)

如果一个元素是偶数子元素,使用 even 变体来为其设置样式:

🌐 Style an element if it's an evenly numbered child using the even variant:

<table>  {#each people as person}    <tr class="bg-white even:bg-gray-100 ...">      <!-- ... -->    </tr>  {/each}</table>

:first-of-type

如果元素是其类型的第一个子元素,则使用 first-of-type 变体为其设置样式:

🌐 Style an element if it's the first child of its type using the first-of-type variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="ml-2 first-of-type:ml-6 ...">      <!-- ... -->    </a>  {/each}</nav>

:last-of-type

如果元素是其类型的最后一个子元素,则使用 last-of-type 变体为其设置样式:

🌐 Style an element if it's the last child of its type using the last-of-type variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mr-2 last-of-type:mr-6 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:only-of-type

如果元素是其类型的唯一子元素,可以使用 only-of-type 变体进行样式设置:

🌐 Style an element if it's the only child of its type using the only-of-type variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mx-2 only-of-type:mx-6 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:nth-child()

使用 nth 变体在特定位置为元素设置样式:

🌐 Style an element at a specific position using the nth variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mx-2 nth-3:mx-6 nth-[3n+1]:mx-7 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:nth-last-child()

使用 nth-last 变体从末尾的特定位置为元素设置样式:

🌐 Style an element at a specific position from the end using the nth-last variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mx-2 nth-last-3:mx-6 nth-last-[3n+1]:mx-7 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:nth-of-type()

使用 nth-of-type 变体为同类型的元素在特定位置设置样式:

🌐 Style an element at a specific position, of the same type using the nth-of-type variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mx-2 nth-of-type-3:mx-6 nth-of-type-[3n+1]:mx-7 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:nth-last-of-type()

使用 nth-last-of-type 变体对同类型的元素从末尾的特定位置进行样式设置:

🌐 Style an element at a specific position from the end, of the same type using the nth-last-of-type variant:

<nav>  <img src="/logo.svg" alt="Vandelay Industries" />  {#each links as link}    <a href="#" class="mx-2 nth-last-of-type-3:mx-6 nth-last-of-type-[3n+1]:mx-7 ...">      <!-- ... -->    </a>  {/each}  <button>More</button></nav>

:empty

如果一个元素没有内容,则使用 empty 变体来设置样式:

🌐 Style an element if it has no content using the empty variant:

<ul>  {#each people as person}    <li class="empty:hidden ...">{person.hobby}</li>  {/each}</ul>

:disabled

使用 disabled 变体为禁用状态的输入设置样式:

🌐 Style an input when it's disabled using the disabled variant:

<input class="disabled:opacity-75 ..." />

:enabled

使用 enabled 变体为启用时的输入框设置样式,这在你只想在元素未禁用时应用另一种样式时特别有用:

🌐 Style an input when it's enabled using the enabled variant, most helpful when you only want to apply another style when an element is not disabled:

<input class="enabled:hover:border-gray-400 disabled:opacity-75 ..." />

:checked

使用 checked 变体为选中状态的复选框或单选按钮设置样式:

🌐 Style a checkbox or radio button when it's checked using the checked variant:

<input type="checkbox" class="appearance-none checked:bg-blue-500 ..." />

:indeterminate

使用 indeterminate 变体为不确定状态的复选框或单选按钮设置样式:

🌐 Style a checkbox or radio button in an indeterminate state using the indeterminate variant:

<input type="checkbox" class="appearance-none indeterminate:bg-gray-300 ..." />

:default

使用 default 变体为页面初次加载时的默认选项、复选框或单选按钮设置样式:

🌐 Style an option, checkbox or radio button that was the default value when the page initially loaded using the default variant:

<input type="checkbox" class="default:outline-2 ..." />

:optional

当输入为可选时,使用 optional 变体来设置样式:

🌐 Style an input when it's optional using the optional variant:

<input class="border optional:border-red-500 ..." />

:required

当输入为必填时,使用 required 变体来设置样式:

🌐 Style an input when it's required using the required variant:

<input required class="border required:border-red-500 ..." />

:valid

当输入有效时,使用 valid 变体来设置样式:

🌐 Style an input when it's valid using the valid variant:

<input required class="border valid:border-green-500 ..." />

:invalid

当输入无效时,使用 invalid 变体来设置样式:

🌐 Style an input when it's invalid using the invalid variant:

<input required class="border invalid:border-red-500 ..." />

:user-valid

当输入有效且用户已与之互动时,使用 user-valid 变体来设置输入样式:

🌐 Style an input when it's valid and the user has interacted with it, using the user-valid variant:

<input required class="border user-valid:border-green-500" />

:user-invalid

当输入无效且用户已与其交互时,使用 user-invalid 变体为输入设置样式:

🌐 Style an input when it's invalid and the user has interacted with it, using the user-invalid variant:

<input required class="border user-invalid:border-red-500" />

:in-range

当输入值在指定范围内时,使用 in-range 变体为输入框设置样式:

🌐 Style an input when its value is within a specified range limit using the in-range variant:

<input min="1" max="5" class="in-range:border-green-500 ..." />

:out-of-range

当输入值超出指定范围限制时,使用 out-of-range 变体为输入框设置样式:

🌐 Style an input when its value is outside of a specified range limit using the out-of-range variant:

<input min="1" max="5" class="out-of-range:border-red-500 ..." />

:placeholder-shown

当显示占位符时,使用 placeholder-shown 变体来设置输入样式:

🌐 Style an input when the placeholder is shown using the placeholder-shown variant:

<input class="placeholder-shown:border-gray-500 ..." placeholder="you@example.com" />

:details-content

使用 details-content 变体为 <details> 元素的内容设置样式:

🌐 Style the content of a <details> element using the details-content variant:

<details class="details-content:bg-gray-100 ...">  <summary>Details</summary>  This is a secret.</details>

:autofill

当浏览器使用 autofill 变体自动填充输入框时,为其设置样式:

🌐 Style an input when it has been autofilled by the browser using the autofill variant:

<input class="autofill:bg-yellow-200 ..." />

:read-only

当输入框为只读时,使用 read-only 变体进行样式设置:

🌐 Style an input when it is read-only using the read-only variant:

<input class="read-only:bg-gray-100 ..." />
TailwindCSS 中文网 - 粤ICP备13048890号