Tailwindcss, Frontend, Css

How to use data attribute variants in Tailwind CSS

How to use data attribute variants in Tailwind CSS - Stijn Elskens Cover
Tailwind CSS just got even better with the new Data Attribute Variants feature. Learn how to use this powerful feature to create stunning designs for your web projects.

Introduction to Data Attribute Variants in Tailwind CSS v3.2 Data Attribute Variants are a new feature in the latest version of Tailwind CSS that allow you to add custom styles to your web projects using data attributes. This means that you can easily create attribute-based styling that is both responsive and customizable. With Data Attribute Variants, you can apply different styles to the same element based on the value of its data attribute. This makes it easy to create custom designs for specific use cases, such as differentiating between different states of a component.

To get started with Data Attribute Variants in Tailwind CSS, you need to update to version 3.2 or later. Once you have done that, you can use the data attribute variant for styling here an example for a success alert:

<div data-status="success" class="data-[status=success]:bg-green-200 p-4" role="alert">
    <p>
        Successfully saved!
    </p>
</div>


This can be useful for when using 3rd-party libraries or situations where you can't pass framework JS props. Your code can be simplified as there is no need to write conditionals for the styles.

How to target child elements using the `.group` class. Add the group class on the element where the data attribute is set, and then prefix your data variant class with `group-`:

<div data-status="success" class="group data-[status=success]:bg-green-200 p-4" role="alert">
    <p class="group-data-[status=succes]:text-green-700">
        Successfully saved!
    </p>
</div>


A full example on how it would look:

<div data-status="success" class="group data-[status=success]:bg-green-200 data-[status=warning]:bg-yellow-200 data-[status=warning]:bg-danger-200 p-4" role="alert">
    <p class="group-data-[status=succes]:text-green-700 group-data-[status=warning]:text-yellow-700 group-data-[status=danger]:text-red-700">
        Successfully saved!
    </p>
</div>


Based on the value of the data attribute, the components get the right style.

More info here: https://tailwindcss.com/blog/tailwindcss-v3-2#data-attribute-variants