Using Tailwind CSS in your Drupal Theme

What is Tailwind?

Tailwind is a utility-first CSS framework for rapidly building custom user interfaces.

It generates a number of utility classes that you can add to your theme's markup to apply different styling, as well as the ability to apply classes to other markup and create components comprised of utility classes using a custom @apply PostCSS directive.

Initial Configuration

The installation and configuration steps are essentially the same as those outlined within the Tailwind documentation, and should be performed within your custom theme's directory (e.g. sites/all/themes/custom/mytheme for Drupal 7 or themes/custom/mytheme for Drupal 8:

  1. Require PostCSS and Tailwind via npm or yarn.
  2. Generate a configuration file using ./node_modules/.bin/tailwind init.
  3. Tweak the settings as needed.
  4. Add a postcss.config.js file.
  5. Configure your build tool (Gulp, Grunt, Webpack).
  6. Generate the CSS.
  7. Include a path to the generated CSS in your MYTHEME.info, MYTHEME.info.yml or MYTHEME.libraries.yml file.

PostCSS Configuration

Create a postcss.config.js file and add tailwindcss as a plugin, passing the path to the config file:

module.exports = {
    plugins: [
        require('tailwindcss')('./tailwind.js'),
    ]
}

Configuration for Drupal

There are some configuration settings within tailwind.js that you’ll need to change to make things work nicely with Drupal. These are within the options section:

options: {
    prefix: 'tw-',
    important: true,
    ...
}

Prefix

By adding a prefix like tw-, we can ensure that the Tailwind classes don’t conflict with core HTML classes like block. We can also ensure that they won't conflict with any other existing HTML or CSS.

No prefix:

With prefix:

Important

We can also set the !important rule on all Tailwind’s generated classes. We need to do this if we want to override core styles which have more specific rules.

For example: if I had this core markup then the left margin added by tw-ml-4 would be overridden by core’s .item-list ul styling.

<div class="item-list">
  <ul class="tw-ml-4">
    ...
  </ul>
</div>

With the !important rule enabled though, the Tailwind’s class takes precedence and is applied.

Example

For an example of Tailwind within a Drupal 8 theme, see the custom theme for the Drupal Bristol website on GitHub.

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.