Using Tailwind within CSS

One thing that often gets neglected when discussing about Tailwind’s utility class approach is that it isn’t limited to that. You can use Tailwind’s directives and functions to make use of Tailwind’s presets inside your own CSS. That could go as far as writing completely your own class references and only using the styling inside your CSS file.

The nice thing is that it integrates well, even from a layer / cascading perspective due to the layer directives we can use. Here’s a quick example of what it’s about:

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

@layer base {
  h1 {
    @apply text-3xl;
    @apply font-bold;
    /* Mixing is allowed, too: */
    color: #000;
  }

  blockquote {
    @apply text-center;
    @apply max-w-5xl;
    @apply mx-auto;
    @apply my-8;
    @apply text-lg;
    @apply font-semibold;
    @apply text-blue-700;
  }

  blockquote footer::before {
    content: '— ';
  }

  hr {
    @apply my-8;
  }
}

By default, Tailwind’s logic is to have no special styles unless you add the classes. For typographic stuff there’s a plugin handling that for you but as we’ve seen in the code snippet above, it’s easy to customise all that yourself.

At a first glance it doesn’t look very pretty but it’s mainly that we’re not used to this yet. After using this for a couple of hours, it makes sense and together with Tailwind’s intellisense plugin for VS Code it’s amazingly fast to write CSS like that:

hr {
  @apply my-8;
}

instead of

hr {
  margin-top: 4rem;
  margin-bottom: 4rem;
}

For the sake of completeness I want to mention that a shorthand margin isn’t the same as it always defines the x-axis as well which Tailwind’s directive doesn’t so I had to compare the long-hand margin notation with the @apply directive.

What for?

There are two main use cases to use this feature in my opinion: First is Content Management Systems (CMS) which allow user content input. If we’re not using Tailwind plugins or other stuff here, we’d need to customise our CMS rich text editor to output all the required Tailwind classes. It’s way easier to add the directives for all the common rich-text styles to your stylesheet as shown above.

Even if we’re using TailwindCSS for styling a website project, I always end up writing a couple of custom rules and styles. Or widget styles that aren’t compatible with Tailwind like the many newsletter integrations available out there. You can easily add the code from the vendor to your Tailwind sheet and have it concatenated, optimised and minified via the Tailwind CLI (or Tailwind node module).

I hope you enjoy this little trick to customise Tailwind easily.

Written on as Article