Optimizing for Production - Tailwind CSS (2024)

Overview

Using the default configuration, the development build of Tailwind CSS is 3645.2kB uncompressed, 294.2kB minified and compressed with Gzip, and 72.8kB when compressed with Brotli.

UncompressedMinifiedGzipBrotli
3645.2kB2936.0kB294.2kB72.8kB

This might sound enormous but the development build is large by design.

To make the development experience as productive as possible, Tailwind generates thousands of utility classes for you, most of which you probably won’t actually use.

Think of Tailwind like a giant box of LEGO — you dump it all out on the floor and build what you want to build, then when you’re done you put all the pieces you didn’t use back into the box.

For example, Tailwind generates margin utilities for every size in your spacing scale, for every side of an element you might want to apply margin to, at every breakpoint you are using in your project. This leads to hundreds of different combinations that are all important to have available, but not all likely to be needed.

When building for production, you should always use Tailwind’s purge option to tree-shake unused styles and optimize your final build size. When removing unused styles with Tailwind, it’s very hard to end up with more than 10kb of compressed CSS.

Writing purgeable HTML

Before getting started with the purge feature, it’s important to understand how it works and build the correct mental model to make sure you never accidentally remove important styles when building for production.

PurgeCSS (the library we use under the hood) is intentionally very naive in the way it looks for classes in your HTML. It doesn’t try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:

/[^<>"'`\s]*[^<>"'`\s:]/g

This basically matches any string separated by spaces, quotes or angle brackets, including HTML tags, attributes, classes, and even the actual written content in your markup.

That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise PurgeCSS won’t know to preserve those classes.

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

As long as a class name appears in your template in its entirety, PurgeCSS will not remove it.

Removing unused CSS

Basic usage

To get started, provide an array of paths to all of your template files using the purge option:

// tailwind.config.jsmodule.exports = { purge: [ './src/**/*.html', './src/**/*.vue', './src/**/*.jsx', ], theme: {}, variants: {}, plugins: [],}

This list should include any files in your project that reference any of your styles by name. For example, if you have a JS file in your project that dynamically toggles some classes in your HTML, you should make sure to include that file in this list.

When using important with the selector strategy, be sure that the template file that includes your root selector is included in your purge configuration, otherwise all of your CSS will be removed when building for production.

Now whenever you compile your CSS with NODE_ENV set to production, Tailwind will automatically purge unused styles from your CSS.

Enabling manually

If you want to manually control whether unused styles should be removed (instead of depending implicitly on the environment variable), you can use an object syntax and provide the enabled option, specifying your templates using the content option:

// tailwind.config.jsmodule.exports = { purge: { enabled: true, content: ['./src/**/*.html'], }, // ...}

We recommend only removing unused styles in production, as removing them in development means you need to recompile any time you change your templates and compiling with PurgeCSS enabled is much slower.

Safelisting specific classes

If you need to safelist specific classes to make sure they are never accidentally removed from your CSS (perhaps because they are used in content that comes from a database or similar), you can use our safelist purge option:

// tailwind.config.jsmodule.exports = { purge: { content: ['./src/**/*.html'], safelist: [ 'bg-blue-500', 'text-center', 'hover:opacity-100', // ... 'lg:text-right', ] }, // ...}

Transforming content

Sometimes you are authoring content in a format that compiles to HTML, and it would be better to compile that content to HTML before looking for potential classes. A great example of this is working with markdown files.

You can use the transform option to tell Tailwind to transform any file matching a specific extension before it looks for classes to guarantee the most accurate results:

// tailwind.config.jslet remark = require('remark')module.exports = { purge: { content: ['./src/**/*.{html,md}'], transform: { md: (content) => { return remark().process(content) } } }, // ...}

Customizing extraction logic

If you need to override the logic Tailwind uses to detect classes in the content of a specific file type, you can use the extract option to provide a function that will be used to detect potential classes in matching files:

// tailwind.config.jsmodule.exports = { purge: { content: ['./src/**/*.{html,md}'], extract: { md: (content) => { return content.match(/[^<>"'`\s]*/) } } }, // ...}

This is an advanced feature and most users won’t need it. The default extraction logic in Tailwind works extremely well for almost all projects.

Preserving HTML elements

By default, Tailwind will preserve all basic HTML element styles in your CSS, like styles for the html, body, p, h1, etc. tags. This is to minimize accidentally over-purging in cases where you are using markdown source files for example (where there is no actual h1 tag present), or using a framework that hides the document shell (containing the html and body tags) somewhere in a vendor directory (like Next.js does).

If you want to disable this behavior, you can set preserveHtmlElements to false:

See Also
Unminify CSS

// tailwind.config.jsmodule.exports = { purge: { preserveHtmlElements: false, content: ['./src/**/*.html'], }, // ...}

We generally do not recommend this and believe that the risks outweigh the benefits, but we’re not the cops, do whatever you want.

Purging specific layers

By default, Tailwind will purge all styles in the base, components, and utilities layers. If you’d like to change this, use the layers option to manually specify the layers you’d like to purge:

// tailwind.config.jsmodule.exports = { purge: { layers: ['components', 'utilities'], content: ['./src/**/*.html'], }, // ...}

Removing all unused styles

By default, Tailwind will only remove unused classes that it generates itself, or has been explicitly wrapped in a @layer directive. It will not remove unused styles from third-party CSS you pull in to your project, like a datepicker library you pull in for example.

/* These styles will all be purged */@tailwind base;@tailwind components;@tailwind utilities;/* These styles will be purged */@layer components { .btn { /* ... */ }}/* These styles will not be purged */.flatpickr-innerContainer { /* ... */ }.flatpickr-weekdayContainer { /* ... */ }.flatpickr-weekday { /* ... */ }

This is to avoid accidentally removing styles that you might need but are not directly referenced in your templates, like classes that are only referenced deep in your node_modules folder that are part of some other dependency.

If you really want to remove all unused styles, set mode: 'all' and preserveHtmlElements: false and be very careful to provide the paths to all files that might reference any classes or HTML elements:

// tailwind.config.jsmodule.exports = { purge: { mode: 'all', preserveHtmlElements: false, content: [ './src/**/*.js', './node_modules/flatpickr/**/*.js', ], }, // ...}

We do not recommend this, and generally find you get 99% of the file size benefits by sticking with the more conservative default approach.

Removing unused keyframes

PurgeCSS does not remove unused @keyframes rules by default, so you may notice some animation related styles left over in your stylesheet even if you aren’t using them. You can remove these using PurgeCSS’s keyframes option under options:

// tailwind.config.jsmodule.exports = { purge: { content: ['./src/**/*.html'], options: { keyframes: true, }, }, // ...}

PurgeCSS options

If you need to pass any other options directly to PurgeCSS, you can do so using options:

// tailwind.config.jsmodule.exports = { purge: { content: ['./src/**/*.html'], // These options are passed through directly to PurgeCSS options: { safelist: ['bg-red-500', 'px-4'], blocklist: [/^debug-/], keyframes: true, fontFace: true, }, }, // ...}

A list of available options can be found in the PurgeCSS documentation.

Alternate approaches

If you can’t use PurgeCSS for one reason or another, you can also reduce Tailwind’s footprint by removing unused values from your configuration file.

The default theme provides a very generous set of colors, breakpoints, sizes, margins, etc. to make sure that when you pull Tailwind down to prototype something, create a CodePen demo, or just try out the workflow, the experience is as enjoyable and fluid as possible.

We don’t want you to have to go and write new CSS because we didn’t provide enough padding helpers out of the box, or because you wanted to use an orange color scheme for your demo and we only gave you blue.

This comes with a trade-off though: the default build is significantly heavier than it would be on a project with a purpose-built configuration file.

Here are a few strategies you can use to keep your generated CSS small and performant.

Limiting your color palette

The default theme includes a whopping 84 colors used for backgrounds, borders, text, and placeholders, all of which also have hover: and focus: variants, as well as responsive variants at the six default screen sizes.

By default, there are thousands of classes generated to accommodate these colors, and it makes up close to half of the final build size.

Very few projects actually need this many colors, and removing colors you don’t need can have a huge impact on the overall file size.

Here’s how using a smaller color palette affects the final size:

ColorsOriginalMinifiedGzipBrotli
84 (default)3645.2kB2936.0kB294.2kB72.8kB
502805.8kB2231.3kB238.7kB59.3kB
252177.6kB1702.8kB198.3kB50.6kB

Removing unused breakpoints

Since almost every Tailwind utility is copied for every screen size, using fewer screen sizes can have a huge impact on the overall file size as well.

Here’s how defining fewer screens affects the output:

BreakpointsOriginalMinifiedGzipBrotli
5 (default)3645.2kB2936.0kB294.2kB72.8kB
32395.9kB1936.0kB196.2kB62.3kB
21781.4kB1446.0kB147.4kB57.3kB
11167.3kB956.3kB98.6kB52.5kB

If you only need 3 screen sizes and 35 colors, you're down to 46.8kB compressed without changing anything else.

Disabling unused core plugins and variants

If you don’t expect to need a certain utility plugin in your project at all, you can disable it completely by setting it to false in the corePlugins section of your config file:

// tailwind.config.jsmodule.exports = { // ... corePlugins: { float: false }}

If you only need a handful of utilities, you can pass an array to corePlugins with the utility plugins you want to keep.

// tailwind.config.jsmodule.exports = { // ... corePlugins: [ 'margin', 'padding' ]}

The above would disable all utilities except margin and padding.

If you need a utility but don’t need the responsive versions, set its variants to an empty array to generate 83% fewer classes:

module.exports = { // ... variants: { appearance: [] }}

These are mostly small wins compared to limiting your color palette or using fewer breakpoints, but they can still add up.

Optimizing for Production - Tailwind CSS (2024)

FAQs

Is Tailwind CSS good for production? ›

When building for production, you should always use Tailwind's purge option to tree-shake unused styles and optimize your final build size. When removing unused styles with Tailwind, it's very hard to end up with more than 10kb of compressed CSS.

Is Tailwind CSS enough? ›

Tailwind is the easiest and simplest part of any project I work on. I can't imagine I'll build anything big without it. Tailwind CSS has alleviated so many problems we've all become accustomed to with traditional CSS that it makes you wonder how you ever developed websites without it.

How difficult is Tailwind CSS? ›

It's very beginner-friendly. While building web pages, you won't even need to leave your HTML file! You don't have to worry about unnecessary code, PurgeCSS will take care of it. You can even make your own classes, so you won't have to repeat the same code again and again.

Does Netflix use Tailwind CSS? ›

For example, Netflix uses Tailwind for Netflix Top 10 and the entire website delivers only 6.5kB of CSS over the network.

Why don't big companies use Tailwind CSS? ›

Inconsistent Design and Difficult Updates

Instead of adjusting it in one place (as you would in a traditional CSS or SASS file), you'd need to go through all the HTML files and change the utility classes individually. This can be time-consuming and error-prone, particularly in large projects with numerous HTML files.

When to not use Tailwind? ›

Don't use Tailwind for a design system (2021) | Hacker News. because the complexity of reading and writing all of the classes is just too much. At that point, you've just reinvented CSS classes.

Do professionals use Tailwind? ›

My company switched from Scss to Tailwind 6 months ago and pretty sure we will stick with it for all our future projects, as it is a lot easier to manage. In VSC, we use this extension to sort the classes so it's always the same order for everyone.

What is Tailwind CSS weakness? ›

Tailwind CSS's weaknesses

Second, utility classes clutter the HTML and make it harder to read. Third, because Tailwind CSS focuses on utility classes, it doesn't have built-in components as Bootstrap does. Creating your own components can be time-consuming, especially for complex UIs.

What is the criticism of Tailwind CSS? ›

Tailwind is incapable of handling code repetition on its own. Its methods for dealing with this issue are highly tied to the IDE or to libraries and frameworks for templating or components, such as React, Vue, or even vintage ones like Nunchucks.

Is it better to learn Tailwind or Bootstrap? ›

Learning Curve: Bootstrap is generally easier for beginners, while Tailwind CSS offers more control for those willing to learn. Development Speed: Bootstrap allows for quicker prototyping, whereas Tailwind CSS is better for tailored designs.

What is better than Tailwind CSS? ›

10 Best Tailwind Alternatives in 2024
  • Bulma.
  • Foundation.
  • Materialize CSS.
  • Semantic UI.
  • UIkit.
  • Tachyons.
  • Spectre CSS.
  • Pure CSS.
Apr 28, 2024

Is Tailwind beginner friendly? ›

Utility-First Methodology is Beginner-Friendly

Tailwind has over 500 styles ready for you to use. You can easily mix different styles to make your site look just how you want. Making changes is as simple as swapping out one style for another.

Is Tailwind CSS actually good? ›

Furthermore, Tailwind's integration with PurgeCSS helps remove unused CSS for an economical, prompt build. Essentially, while Bootstrap is geared toward quick, uniform designs, Tailwind is great for seasoned developers seeking accuracy in their designs. Both are legitimate choices in 2023.

Which big companies use Tailwind CSS? ›

Companies Currently Using Tailwind CSS
Company NameWebsiteSub Level Industry
Backyard Products, LLCbackyardproducts.comConsumer Goods
Nisumnisum.comManagement & Business Consulting
Degreeddegreed.comSoftware Manufacturers
Fiservfiserv.comBanking
2 more rows

Why is Tailwind CDN not good for production? ›

Using the Tailwind CSS CDN for production is not recommended for most projects. While it offers ease of use, it lacks the benefits of a custom build process, such as purging unused CSS, which can lead to larger CSS files and slower websites.

Can I use Tailwind CSS for commercial use? ›

Can I use Tailwind UI for client projects? Yes! As long what you're building is a custom website developed for a single client, you can totally use components and templates in Tailwind UI to help build it. The only thing you can't do is use Tailwind UI to build a website or template that is resold to multiple clients.

What is the disadvantage of Tailwind CSS? ›

While Tailwind offers many advantages, it's not without its drawbacks:
  • Verbose Syntax. One of the most common criticisms is that it can lead to verbose and hard-to-read HTML, as all the styles are inline.
  • Learning Curve. ...
  • Tight Coupling. ...
  • Risk of Code Duplication.

Is Tailwind good for performance? ›

“Combined with minification and network compression, [Tailwind CSS] usually leads to CSS files that are less than 10kB, even for large projects. That type of performance is simply unbeatable unless you write your own utility classes.

Top Articles
Disability determination processing time
Difference between Binary and Matrix Compensation Plans
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated:

Views: 6160

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.