Tip 28/72

Use of data attributes

Learn how to use data attributes in TailwindCSS to conditionally style elements and enhance your design flexibility.

Data attributes in TailwindCSS provide a powerful way to conditionally style elements based on specific attributes. This approach enhances your design flexibility and allows you to create more dynamic and context-aware styles.

Basic Usage

You can use data attributes to apply styles conditionally. For example, check if an element has a data-primary attribute and apply the primary styles to it.

<button 
    data-primary 
    className="px-3 h-9 rounded-md border shadow-sm text-sm text-white flex items-center justify-center transition-[filter] duration-200 hover:brightness-90 data-primary:bg-indigo-600 data-primary:border-indigo-700 dark:data-primary:border-white/10 data-destructive:bg-red-600 data-destructive:border-red-700 dark:data-destructive:border-white/10"
>
    Primary
</button>

Specific Value

You can also check if an element has a data-* attribute with a specific value and apply styles accordingly.

<button 
    data-variant="primary" 
    className="px-3 h-9 rounded-md border shadow-sm text-sm text-white flex items-center justify-center transition-[filter] duration-200 hover:brightness-90 data-[variant=primary]:bg-indigo-600 data-[variant=primary]:border-indigo-700 dark:data-[variant=primary]:border-white/10 data-[variant=destructive]:bg-red-600 data-[variant=destructive]:border-red-700 dark:data-[variant=destructive]:border-white/10"
>
    Primary
</button>

Custom Variant

Create custom data attributes and apply styles based on the value of the attribute. This is useful when you have common data attributes in your project with specific values.

1. Create custom data attributes

@custom-variant data-primary (&[data-variant~="primary"]);

2. Apply styles based on the custom data attribute

<button 
    data-variant="primary" 
    className="px-3 h-9 rounded-md border shadow-sm text-sm text-white flex items-center justify-center transition-[filter] duration-200 hover:brightness-90 data-primary:bg-indigo-600 data-primary:border-indigo-700 dark:data-primary:border-white/10"
>
    Primary
</button>

Conclusion

Using data attributes in TailwindCSS allows you to conditionally style elements based on specific attributes, providing greater flexibility and control over your designs. By leveraging data attributes, you can create more dynamic and context-aware styles, enhancing the overall user experience.