Forcing a Classname into TailwindCSS Compilation

Today I learned that if you want to add custom modifications to a TailwindCSS classname that's not used in the content section, you can force it into compilation by adding it to the safelist section of the configuration file using @apply.

I faced this issue when I was trying to customize the gatsby-highlight classname, which is injected by gatsby-transformer-remark and/or gatsby-remark-prismjs, but not used in any content documents or layout components.

/* global.css */

@layer components {
  .gatsby-highlight {
    @apply cover-full lg:cover-almost 2xl:cover-half;
    @apply text-xs lg:text-sm;
  }
}

To overcome this issue, you can add the missing classname to the safelist section of the tailwind.config.js file. The safelist is a list of classes that TailwindCSS will always include in the final CSS file, regardless of whether they are used in the content or not.

Here is an example of adding gatsby-highlight to the safelist section of the configuration file:

// tailwind.config.js

module.exports = {
  content: ['./content/**/*.md', './src/**/*.{js,jsx,ts,tsx}'],
  // ...
  safelist: ['gatsby-highlight']
};

However, adding too many classes to the safelist can result in a larger final CSS file, which can impact your website's performance. Therefore, it's important to only include classes in the safelist that you actually need.

Next time you need to apply custom modifications to a TailwindCSS classname that's not used in the content section, remember that you can force it into compilation by adding it to the safelist section of the configuration file.

  • #frontend
  • #tailwindcss
  • #gatsbyjs