6

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

user84296
  • 111
  • 1
  • 2
  • 5

5 Answers5

24

Updated answer as of 2022/10/30

As of Tailwind v3.2, data attribute variants are supported.

<!-- 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>

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

landen
  • 361
  • 2
  • 6
  • Sweet, that's exactly what I was looking for! In my case, I needed to select the parent element's data attribute, but that can easily be achieved by using the `group` selector: `group-data[attr=value]:hidden` – Robin van Baalen Dec 23 '22 at 18:02
11

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.

Zach Inglis
  • 1,242
  • 1
  • 14
  • 28
  • Thank you. It works and beautiful but I could not figure out why it does not work with `peer-ben:`? Do you have any suggestion? – 1t1e1 Sep 29 '22 at 13:57
1

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

Muhammad Gata
  • 281
  • 1
  • 4
0

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;
}
Mark Kvetny
  • 664
  • 6
  • 19
-3

I think you are looking for the best syntax for state selection:

<a class="bg:blue[data-author=Ben]" data-author="Ben">Ben</a>

All native CSS selectors can be applied:

<button class="opacity:.5[disabled]" disabled>Submit</button>

It's enabled with zero configuration and the syntax is very similar to native CSS.

Aron
  • 10
  • 1
  • 2
  • 2
    The question is specifically about tailwindcss, not Master css. And you don't even mention that your solution isn't about tailwindcss. – MnZrK Dec 14 '22 at 02:53