Gauntlet DesignsArticlesAI Solutions

No More Class Spam With Tailwind

As TailwindCSS continues its meteoric rise in popularity over the last couple of years, a persistent issue has surfaced in the eyes of many developers—class overload. TailwindCSS often leads to a flurry of classes cluttering your HTML, making it hard to keep track. For instance, consider the attempt to style a primary button:

<div class="bg-sky-400 text-black hover:bg-sky-500 active:bg-sky-800 active:text-white px-5 py-3>

Not only is this a long list of classes, but it also only covers basic styling aspects like colors and padding. Normally, you'd need to add more classes for transitions, margins, and positioning.

Unlocking Tailwind's Potential with Layers

Tailwind differs from frameworks like Bootstrap and Material Design in that it doesn't provide ready-made components. However, this opens the door to crafting your own components, and one effective approach is to use layers configured in your CSS files. If you're working with NextJS, you'd typically place this in the globals.css file.

The base setup for a globals.css file using TailwindCSS is:

globals.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@apply

The real magic happens when you create custom classes that group a set of Tailwind classes into one, neatly organized package. Let's move those primary button classes into the globals.css file:

globals.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .primary-btn {
    @apply bg-sky-400 text-black hover:bg-sky-500 active:bg-sky-800 active:text-white px-5 py-3
  }
}

Then in our html file.

<div class="primary-btn">

This approach lets you tuck away your extensive class lists into a CSS file where they belong. As you add more or tweak existing classes, your Git history remains focused on a single file, reducing chaos.

Tailwind Custom Colors

We can further reduce the git churn by using the tailwind config to define custom variables and colors that we use throughout the components.

tailwind.config.js

...
theme: {
  colors: {
    'primary': '#7dd3fc',
    'primary-dark': '#0ea5e9',
    'primary-darker': '#0369a1'
  }
}
...

Another technique to minimize Git churn is by harnessing the power of Tailwind's custom color configuration. By defining custom variables and colors in your tailwind.config.js file, you can create a consistent color scheme across your components. For example:

...
@apply bg-primary hover:bg-primary-dark active:bg-primary-darker ...
...

By using these colors consistently throughout your styles, you can make substantial changes to your website's look and feel without creating excessive Git churn, even within the CSS file.

Gauntlet Designs
Contact us
contact@gauntletdesigns.com
Gauntlet Designs