Keep Specificity in Check when Working with Tailwind

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson, we learn different ways to handle specificity in Tailwind, depending on the context of your project. We look at how your should order your CSS declarations in your stylesheet, discover the “important” config option for a “utility-last” approach.

Instructor: [00:00] One of the great features of utility classes is that they are extremely low in specificity. Take this simple H2 headline with two utility classes. Say that I want to override these classes with custom CSS.

[00:13] I'll add a Hero headline class to my H2. In my CSS, I'll add some styles after my Tailwind utilities. With a simple class name, which has very low specificity, I was able to override the utility classes. Now, let's reverse the scenario.

[00:29] What if you want to use Tailwind on top of existing custom CSS in a more utility-last approach? Let's see what happens if I move my class names before Tailwind here. As you can see, my Tailwind utility classes have now taken over, because they have the same level of specificity, but are declared later in the style sheet.

[00:50] This is nice, but what if the custom CSS is more specific? Now, our utility classes are not able to override this custom CSS. Does that mean Tailwind can't be used as a utility-last framework? No, it doesn't. The Tailwind config file provides an option, at the very bottom of the file, to mark the utility classes as important.

[01:12] Setting that option to true will make sure that Tailwind utility classes always override other class names. As you can see now, all our generated utility classes are marked with important. If I set the option to false, the important disappears. Turn it back on, and it's back.