Home Web Front-end CSS Tutorial How to use Tailwinds `safelist` to handle dynamic classes

How to use Tailwinds `safelist` to handle dynamic classes

Aug 23, 2024 pm 06:30 PM

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
};
Copy after login

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/,
  },
],
Copy after login

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/,
  },
],
Copy after login

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'
Copy after login

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;
  }
}
Copy after login

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 of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

While You Weren't Looking, CSS Gradients Got Better While You Weren't Looking, CSS Gradients Got Better Apr 11, 2025 am 09:16 AM

One thing that caught my eye on the list of features for Lea Verou's conic-gradient() polyfill was the last item:

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

The Three Types of Code The Three Types of Code Apr 11, 2025 pm 12:02 PM

Every time I start a new project, I organize the code I’m looking at into three types, or categories if you like. And I think these types can be applied to

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn't have to be the case. Let’s look at how PHP projects can enforce a basic

See all articles