Tailwind CSS Course
Tailwind CSS
/
Advanced

Data Attribute Selectors

Definition

Using the `data-*` variant to style elements based on custom HTML data attributes.

Explain Like I'm New

A modern alternative to `peer` and `group` classes. In React, you dynamically apply `data-state="open"` to a dropdown menu. You can then use Tailwind's `data-[state=open]:opacity-100` to style it. This creates an incredibly clean separation between JavaScript logic and CSS styling.

Real World Example

The Radix UI library exclusively uses `data-state` attributes to tell the DOM what is happening. Tailwind perfectly intercepts these attributes to apply styles.

Common Use Cases

  • •Headless UI styling
  • •Complex interactive states

Interactive Example

Interview Questions

basic

  • What Tailwind variant allows you to style an element when it has `data-active="true"` in its HTML?

intermediate

  • Why is styling based on `data-*` attributes often preferred over toggling an `.is-active` CSS class?

Flash Cards

Question

Which variant?

Click to reveal answer
Answer

`data-[active=true]:` (e.g., `data-[active=true]:bg-blue-500`).

Question

Why preferred over classes?

Click to reveal answer
Answer

Because `data-*` attributes can hold string values (`data-state="loading"`, `data-state="success"`), making them much more expressive and readable than having a mess of separate classes like `.is-loading` and `.is-success`.