Published on

How to Group Classes in Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Group Classes in Tailwind CSS

Tailwind CSS is a utility-first framework that provides a large number of utility classes. While this is powerful, it can lead to long class lists that make code harder to read and maintain. Here’s how to group classes effectively in Tailwind CSS.

1. Using @apply (Requires Tailwind via PostCSS)

If you're using Tailwind with a build process (such as in a project with PostCSS or a framework like Next.js), you can group classes using @apply in your CSS files.

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

@layer components {
  .nav-link {
    @apply text-xl duration-500 md:hover:text-yellow-300;
  }

  .nav-item {
    @apply px-4 py-6 text-white duration-500 hover:bg-yellow-500 md:py-0 md:hover:bg-transparent;
  }
}

Then, in your HTML/JSX:

<ul>
  <li class="nav-item">
    <a href="#" class="nav-link">Home</a>
  </li>
  <li class="nav-item">
    <a href="#" class="nav-link">About Us</a>
  </li>
</ul>

2. Using Custom Classes in HTML (CDN-Friendly Approach)

If you're using Tailwind via a CDN (without a build process), @apply won’t work. However, you can still group classes manually:

<style>
  .nav-item {
    padding: 1.5rem 1rem;
    color: white;
    transition-duration: 500ms;
  }
  .nav-item:hover {
    background-color: yellow;
  }
  @media (min-width: 768px) {
    .nav-item {
      padding: 0.5rem 1rem;
      background: transparent;
    }
  }
</style>

<ul>
  <li class="nav-item"><a href="#">Home</a></li>
  <li class="nav-item"><a href="#">About Us</a></li>
</ul>

3. Using JavaScript for Dynamic Class Management

Another approach is to define Tailwind classes in JavaScript and use them dynamically in a framework like React or Vue.

React Example:

const styles = {
  navItem: 'px-4 py-6 md:py-0 hover:bg-yellow-500 md:hover:bg-transparent text-white duration-500',
  navLink: 'text-xl md:hover:text-yellow-300 duration-500',
}

function Navigation() {
  return (
    <ul>
      <li className={styles.navItem}>
        <a href="#" className={styles.navLink}>
          Home
        </a>
      </li>
      <li className={styles.navItem}>
        <a href="#" className={styles.navLink}>
          About Us
        </a>
      </li>
    </ul>
  )
}

4. Using CSS Variables with Tailwind

You can also use CSS variables to group styles:

:root {
  --nav-item: px-4 py-6 md: py-0 hover: bg-yellow-500 md: hover: bg-transparent text-white
    duration-500;
}

Then apply it dynamically in Tailwind-supported environments:

<li class="var(--nav-item)">
  <a href="#" class="text-xl duration-500 md:hover:text-yellow-300">Home</a>
</li>