How to target elements with a specific data attribute with Tailwind CSS?

Viewed 2102

I have several message boxes and each box has a data-author attribute.

If I want to apply styles to these message boxes in CSS, I can just do:

[data-author="Ben"] {
  background-color: blue;
}

But I'm not sure how to do this with Tailwind CSS or whether it's even possible. Any idea?

Thanks

3 Answers

You can do this by adding a variant. In your tailwind.config.js:

Add const plugin = require('tailwindcss/plugin') at the top of the page.

Then in your export add:

  plugins: [
    plugin(({ addVariant }) => {
      addVariant('ben', '&[data-author="Ben"]')
    }),
  ]

All you have to do is then use it how you want: ben:bg-blue-500

You would need to create a new one for each individual author though, or come up with a convention for grouping them by colors.

you can use the syntax you used above. for implementation problems, you can use the @apply directive which can directly call the utility class from tailwind

In addition, you can also apply a color that is outside the tailwind color by using an arbitrary value

[data-author="Ben"] {
  @apply bg-[#bada55];
}

You can learn more about arbitary value in this article:

https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values

This isn't possible with tailwind, you can only target elements by giving them classes. However, you can still write custom CSS and add styles to it with tailwind's @apply:

[data-author="Ben"] {
  @apply bg-blue-500;
}
Related