How to Add Custom CSS or Classes in TailwindCSS

TailwindCSS provides almost everything you need to design an awesome website. If you see something that doesn’t exist, you can add it to the tailwind config file. But, if you still wish to add custom CSS or custom classes, you can add them to the tailwind input file.

Adding Custom Styles in TailwindCSS

The simplest solution is to add your own classes into the tailwind input file. The input file that contains 3 tailwind directives is used to generate the output CSS file. So, when you add your own classes to the input file, tailwind will use add those classes to the output file. The following example adds a custom class in the tailwind input file. You can check the working code example on the tailwind playground.

Here is the output of the above code.

custom class in tailwindcss

Using @apply Directive in TailwindCSS

When you are working with custom classes in tailwind, you can benefit from the @apply directive. This @apply directive allows you to use the TailwindCSS classes in your custom classes. You can combine as many tailwind classes as you want to make your own custom class. See the example below to understand how the @apply directive works.

Best Practices to Add Custom CSS in Tailwind

The above method works fine to add custom styles or classes but it is recommended to add your own styles into the relevant layer. If you are trying to add buttons you should add those into @components layer and if you are wishing to add your own utility classes, try adding them into @utilities layer. Here is an example to add a button class and a custom utility class into layers. In the example below, 2 new classes are created. You can check the working example on the tailwind playground.

And then in your HTML you can use these classes.

Adding Base Styles in TailwindCSS

If you are not happy with tailwind base styles and you want them to have a default style of your own, you can add your own styles in the tailwind base layer. For example, if you want all your h1 and h2 to have certain font sizes, you can add them to the base layer of TailwindCSS. Check this example that adds the different font sizes in the base layer of TailwindCSS.

You can read more about adding base styles in TailwindCSS for more information.

Conclusion

You can add your own styles in TailwindCSS in 2 different ways. The first method is to create your own classes and add your style or use @apply directive to use tailwind classes. The second method is to add custom styles into the relevant layer using TailwindCSS directives. The second method is recommended as it clearly adds styles into relevant layers. Please read the official documentation for more information about adding custom styles or classes.

 

 

Latest articles

Leave a reply

Please enter your comment!
Please enter your name here

Related articles