search
HomeWeb Front-endCSS TutorialHow to use Tailwinds `safelist` to handle dynamic classes

How to use Tailwinds `safelist` to handle dynamic classes

Tailwind CSS is a popular utility-first CSS framework that allows developers to create custom designs quickly and efficiently. By default, Tailwind CSS generates a wide range of utility classes, which can lead to large file sizes. To address this issue, Tailwind CSS comes with a built-in feature called PurgeCSS that removes unused styles from the production build, making the final CSS file smaller and more performant. However, this automatic removal may sometimes cause issues when certain styles are used dynamically or conditionally in your application. In this article, we'll dive deep into the safelist feature in Tailwind CSS, learn how to whitelist specific styles, and explore various scenarios where using safelist can be helpful.

1. Understanding PurgeCSS in Tailwind CSS

PurgeCSS is a powerful tool that scans your project files for any class names used and removes the unused ones from the final CSS file. This significantly reduces the size of the generated CSS, making your application load faster.

By default, Tailwind CSS includes PurgeCSS configuration that scans your HTML, JavaScript, and Vue files for any class names. You can easily tweak what files are picked up within the content array of the config file.

In some situations, you might need to prevent specific styles from being removed, even if they're not detected in your files. This is where the safelist feature comes into play.

2. Introducing Safelist

Safelist is a feature in Tailwind CSS that allows you to whitelist certain styles so they don't get removed during the purging process. This is particularly useful when you have dynamic class names generated through JavaScript or applied based on user interaction. Another very common use-case for safelist is when colors or styles are driven from a CMS or backend framework. One such example might be a system that allows a website admin to edit the color of a category in a CMS, which in turn changes the color of the nav items for that category. Tailwind won't see the actual class name as the file will contain server-side code that outputs the color.

By adding these class names to the safelist, you ensure that they will always be included in your final CSS file, regardless of whether PurgeCSS can find them in your project files or not.

3. Configuring Safelist in tailwind.config.js

To configure the safelist in your Tailwind CSS project, you need to modify the tailwind.config.js file. The safelist is an array of class names that you want to keep in your final CSS file, even if they're not found in your project files. Here's an example of how to add class names to the safelist:

// tailwind.config.js
module.exports = {
  content: [
    // your content files here
  ],
  safelist: [
    'bg-red-500', 
    'text-white', 
    'hover:bg-red-700'
  ],  
  // other configurations
};

In this example, the bg-red-500, text-white, and hover:bg-red-700 classes are added to the safelist. These classes will always be included in your final CSS file, even if PurgeCSS doesn't find them in your project files.

4. More advanced configurations

If you have a lot of classes to manage within safelist, perhaps due to multiple colors and the need to support variants/modifiers such as :hover, :focus, :active and dark: then it can quickly become very challenging to manage these within safelist. The list will become huge very quickly.

That's where patterns come in. Tailwind support regex within the safelist:

safelist: [
  {
    pattern: /from-(blue|green|indigo|pink|orange|rose)-200/
  },
  {
    pattern: /to-(blue|green|indigo|pink|orange|rose)-100/,
  },
],

With these 2 entries we are effectively adding 12 classes. from-{color}-200 and to-{color}-100, where {color} is all of the colors in the list. It makes it much easier to manage the lists. Remember that tailwind.config.js is just a JavaScript file, so you can manage variables at the top of the file if you're managing lists of colors that are repeated heavily.

It's also possible to define variants for everything within the list without needing to explicitly list them in regex:

safelist: [
  {
    pattern: /text-(blue|green|indigo|pink|orange|rose)-(600|400)/,
    variants: ['hover'],
  },
  {
    pattern: /from-(blue|green|indigo|pink|orange|rose)-200/
  },
  {
    pattern: /to-(blue|green|indigo|pink|orange|rose)-100/,
  },
],

5. Safelist Examples and Use Cases

There are several scenarios where using the safelist feature can be helpful:

Dynamic class names: If you're generating class names dynamically based on some data or user input, PurgeCSS may not detect these classes and remove them from the final CSS file. By adding these dynamic classes to the safelist, you can ensure they're always available in your application.

// Example of a dynamic class name based on user input
const userInput = 'success'; // This value might come from an API or user input
const alertClass = `alert-${userInput}`;

// Generated class name: 'alert-success'

In this example, the alertClass variable generates a class name based on user input or data from an API. Since PurgeCSS can't detect this dynamic class name, you should add it to the safelist in your tailwind.config.js file.

Conditional styles: If you have styles that only apply under specific conditions, such as a dark mode or a mobile view, you can use the safelist to ensure those styles are always included in your final CSS file.

// Example of a conditional style based on a media query
@media (max-width: 767px) {
  .hidden-mobile {
    display: none;
  }
}

In this example, the hidden-mobile class is only applied when the viewport width is less than 768 pixels. Since this class might not be detected by PurgeCSS, you should add it to the safelist in your tailwind.config.js file.

6. Best Practices for Safelisting

When using the safelist feature in Tailwind CSS, keep the following best practices in mind:

  • Only add classes to the safelist that are truly necessary. Adding too many classes can bloat your final CSS file and negate the benefits of PurgeCSS.
  • If you have many dynamic class names or a complex application, consider using a function or regular expression to generate the safelist array. This can help keep your configuration cleaner and more maintainable.
  • Test your production build to ensure that all required styles are included. This can help you catch any issues early on and avoid surprises when deploying your application.

Summary

The safelist feature in Tailwind CSS provides a powerful way to whitelist specific styles and ensure they are included in your final CSS file, even if they are not detected by PurgeCSS. By understanding how to configure the safelist and use it effectively in various scenarios, you can make your Tailwind CSS projects more robust and maintainable. Remember to follow best practices when using the safelist to ensure your final CSS file remains lean and performant.

Feel free to look over the Tailwind Docs on Safelist usage.

The above is the detailed content of How to use Tailwinds `safelist` to handle dynamic classes. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software