Combining variants with the dark mode “class” strategy

The "class" dark mode strategy only targets children element of the element with the dark class.

If you're trying to combine a custom variant with dark mode, make sure you respect this hierarchy.


00:00 Let's say we want to create a new Skin modifier in Tailwind, but we also want this to work with Dark Mode. So you can see here, we're adding a variant called Skin, and it's targeting any element with the Skin class in the parent. And we've also enabled Dark Mode using the class strategy.

00:17 In the HTML tab, we've got four blocks of Markup, but each of the four ones use the exact same utility classes. And you can see the first one is the default color, second one is just Dark, third one just Skin, which is our variant, and the fourth one is Dark and Skin combined to see how it works.

00:35 And looks like the first three elements work just fine, but the Dark and Skin combination does not work. If I scroll down on the last block of HTML, you can see that we applied Dark and Skin on the same element. And that's why it's not working, because in Tailwind, the Dark class targets its children element.

00:53 Let me just hover over a Dark class to show you. So here, if I hover DarkBGIndigo700, you can see we have the Dark selector and then a Space. So Dark is expecting the children element to be styled. When we try to apply both Dark and Skin modifiers together,

01:12 you can see that we have Dark, Space, Skin, which assumes that Skin would be a child element of Dark. And so to make it work, what we need to do is have the Dark class being a parent of the Skin class. And most of the time, if you have the Dark class on the body element for the whole website, that's not going to be a problem.

01:31 But here, what I'm going to do is duplicate this and this div, and then we'll have the Dark one as the first one, and then the Skin class as the second one. And now you can see that the Dark and Skin colors work properly,

01:47 because we're respecting the nested hierarchy between Dark and Skin. And that's it.

More Tips