DEV Community

Hossain MD Athar
Hossain MD Athar

Posted on

How Do You Declare Custom Classes in a Tailwindcss-React-ts project?

Hey fellow developers,

So, picture this: knee-deep in my project, I hit the classic developer's roadblock - the need for custom classes. Here's my journey, a tale of trials and triumphs that might just save you some precious coding time!

The Dilemma of Custom CSS in Tailwind

In the vast tapestry of React Tailwind projects, customizing styles can feel like a puzzle. I explored three paths, each with its quirks and perks. Let's dive in!

1. Wrangling Tailwind Classes in a Variable!

First up, I tried corralling those repetitive Tailwind classes into a variable tucked away in a cozy .ts file. Everything seemed peachy until the day I wanted a little flair, a touch of customization. Spoiler alert: couldn't pull it off. My dreams of a unique twist were dashed. It's like committing to a tattoo; changing your mind becomes a tad complicated.

2. Global Stylesheet Declaration

Moving on, I experimented with declaring a class in a global stylesheet. A good practice, you'd think. Worked like a charm, until I craved more control. Trying to finesse the styles proved trickier than juggling flaming torches. Need a smaller font? Tough luck! And let's not even start on the exclamation marks – felt like I was in a shouting match with my styles. Ugh!

3. The @layer Revelation in index.css!

And here comes the star of the show—the class declared as a component layer. This, my friends, is the holy grail. Why? Because it behaves like any default Tailwind CSS class, and you can customize it without breaking a sweat.

code snap- an example of using @layer for custom class

The Unmatched Prowess of Component Layer Classes

Why do I vouch for the third approach? Brace yourself for the pros:

  • Seamless Overrides: No more banging your head against the wall with !important. The component layer class gracefully accepts overrides like a seasoned actor playing multiple roles.

  • Scoped and Neat: Your styles remain scoped within the component, keeping your project neat and tidy. No more global chaos!

  • Dynamic Customization: Embrace dynamic styles effortlessly. This approach opens the door to a world where your styles adapt and evolve based on dynamic content.

  • Integrates Like a Charm: Remember, it's Tailwind CSS. Your custom class integrates seamlessly, like it was always meant to be there.

So, fellow coders, spill the beans! How do you deck out your project with custom CSS? Let's swap war stories and share the coding wisdom.

*Hint: Feel free to sprinkle in some more details if your secret sauce involves extra flair!

Top comments (0)