How to Optimize Tailwind CSS for Performance and Speed?

Tailwind CSS blog | Published on : 11th January, 2024

Make your Tailwind CSS super fast! See how to reduce the size of your CSS output and make your website load faster with techniques like purging, minifying, and compressing. Increase your design freedom without losing performance.

Techniques for Tailwind CSS Optimization:

Using JIT Mode in Tailwind CSS for Improved Performance:

Tailwind CSS introduced a Just-in-Time (JIT) mode that dynamically generates CSS based on your actual utility usage in the codebase. Enabling JIT mode reduces the overall CSS file size and eliminates the need for manual purging. Follow these steps to update your Tailwind CSS version and configure JIT mode:

Step 1: Update Tailwind CSS

Ensure that you have the latest version of Tailwind CSS installed. You can update it using npm:

npm install tailwindcss@latest

Step 2: Configure JIT Mode

Update your tailwind.config.js file to enable JIT mode. Add the jit property to your configuration:

// tailwind.config.js
module.exports = {
  content: [
    './resources/**/*.html',
    './resources/**/*.js',
  ],
  // Other Tailwind CSS configurations...
  jit: true,
};

Set jit to true to enable JIT mode. The content property specifies the paths to your HTML and JavaScript files.

Step 3: Remove Purge Configuration

Since JIT mode dynamically generates styles based on usage, you no longer need the purge configuration. Remove it from your tailwind.config.js:

// tailwind.config.js
module.exports = {
  // Other Tailwind CSS configurations...
  jit: true,
};

Step 4: Build Your Styles

With JIT mode enabled, you can now build your styles. Use your usual build command, and Tailwind CSS will dynamically generate styles based on your codebase:

npm run build:css

Ensure that your build process includes the necessary commands for compiling your CSS.

By following these steps and enabling JIT mode, Tailwind CSS dynamically generates styles based on your actual utility usage, eliminating the need for manual purging. This leads to a more streamlined and optimized CSS output, contributing to improved performance and faster loading times.

Combining Utilities with @apply:

Assume you have a card component that you want to style consistently across your website. Instead of applying individual utility classes for each styling aspect, you can create a custom class using @apply.

Step 1: Define Your Utility Classes

In a separate file (e.g., utilities.css), define the utility classes you want to use:

/* utilities.css */
.bg-gray-200 {
  background-color: #e0e0e0;
}

.p-4 {
  padding: 1rem;
}

.rounded-md {
  border-radius: 0.375rem;
}

.text-lg {
  font-size: 1.125rem;
  font-weight: bold;
  color: #333;
}

Step 2: Create a Reusable Component Class Using @apply

In another file (e.g., components.css), create a reusable component class using @apply:

/* components.css */
.card {
  @apply bg-gray-200 p-4 rounded-md text-lg;
}

Step 3: Apply the Component Class in Your HTML

In your HTML file (e.g., index.html), include the utility and component stylesheets:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="utilities.css">
  <link rel="stylesheet" href="components.css">
  <title>Card Example</title>
</head>
<body>

<div class="card">
  <!-- Card Content Goes Here -->
  <h2>Title</h2>
  <p>Description...</p>
</div>

</body>
</html>

By applying the card class to your HTML elements, you encapsulate the repetitive utility classes within a single component class, making your HTML cleaner and more maintainable.

Using @apply in this way promotes code reusability and helps manage changes efficiently by updating the component class instead of modifying multiple instances of utility classes in the HTML. This approach aligns with the utility-first nature of Tailwind CSS while providing the flexibility to create consistent and reusable components.

Minifying tailwind CSS:

Minifying Tailwind CSS involves using a tool to remove unnecessary characters and spaces from your Tailwind CSS code, resulting in a smaller file size. You can use a PostCSS plugin called cssnano to minify your Tailwind CSS. Here's a step-by-step guide

Step 1: Install cssnano as a Dependency: Install cssnano as a development dependency using npm

npm install cssnano --save-dev

Step 2: Update your postcss.config.js File

If you don't have a postcss.config.js file in your project, create one. This file is used to configure PostCSS plugins, including cssnano:

// postcss.config.js
module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
    // Add cssnano as the last plugin in the array
    require('cssnano')({
      preset: 'default',
    }),
  ],
};

In the above configuration.

  • TailwindCSS and autoprefixer are assumed to be part of your PostCSS setup. If not, make sure to include them.
  • cssnano is added as the last plugin in the array. It's configured with the preset: 'default' option, which includes various optimizations.

Step 3: Run your Build Process

Run your build process that involves processing your CSS with PostCSS. This may vary depending on your project setup. For example, if you're using Laravel Mix, you might run:

npm run dev

// Or for production:

npm run prod

Step 4: Verify Minification

Check the generated CSS file in your output directory (commonly public/css or similar) to ensure that it's minified. You should see a reduction in file size due to the removal of unnecessary characters and spaces.

By adding cssnano to your PostCSS configuration, you seamlessly integrate Tailwind CSS with the minification process, optimizing your stylesheets for improved loading times. Adjust the configuration based on your project's specific needs and build process.

Example:

  • Without Minification (styles.css)
/* Generated CSS without Minification */

/* ... Tailwind CSS base, components, and utilities ... */

body {
  background-color: #f0f0f0;
  color: #333;
  font-family: 'Arial', sans-serif;
  padding: 20px;
}

/* ... other custom styles ... */
  • With Minification (styles.min.css)
/* Generated CSS with Minification */

/* ... Minified Tailwind CSS base, components, and utilities ... */

body{background-color:#f0f0f0;color:#333;font-family:'Arial',sans-serif;padding:20px}

/* ... other minified custom styles ... */

In summary, minification removes unnecessary characters from the CSS code, resulting in a smaller file size and improved loading speed. While the minified version might be less readable for humans, it is highly efficient for web browsers.

Tree-shaking for Tailwind CSS with Webpack:

Tree-shaking is a technique used by build tools like Webpack to eliminate unused code (including CSS classes) during the build process. It's a powerful optimization method to reduce the file size of your final bundle. Here's how you can leverage tree-shaking with Tailwind CSS and Webpack

Step 1: Install Necessary Packages

Ensure you have the required packages installed. Install postcss-import and postcss-loader to help process your CSS files:

npm install postcss-import postcss-loader --save-dev

Step 2: Configure Webpack

Set up your Webpack configuration to utilize postcss-loader and enable tree-shaking. Make sure you have css-loader and style-loader installed as well:

// webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.js',  // Adjust your entry point
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',  // Add postcss-loader
        ],
      },
    ],
  },
};

By setting up your project to use PostCSS with Webpack, you can take advantage of tree-shaking to eliminate unused CSS classes. This optimization helps reduce the size of your final bundle, resulting in faster load times for your web application.

  • Note: The specifics of the configuration may vary depending on your project setup and requirements. Adjust the paths, loaders, and plugins accordingly.

Purging Unused CSS with Tailwind CSS and PurgeCSS:

Purging unused CSS is a crucial step to optimize the performance of your Tailwind CSS project. By default, Tailwind generates a large CSS file that includes all utility classes. However, many of these classes may go unused in your specific project. Using PurgeCSS helps remove those unused classes, significantly reducing file size and improving performance.

Here's how you can set up PurgeCSS with Tailwind CSS:

Step 1: Install PurgeCSS

Install PurgeCSS as a development dependency in your project:

npm install purgecss --save-dev

Step 2: Configure Tailwind CSS

Set up your tailwind.config.js file to include the paths to your HTML files. This informs PurgeCSS about the used classes 4:

// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.html',  // Adjust the path to your HTML files
    './src/**/*.js',    // Adjust the path to your JavaScript files
  ],
  // Other Tailwind CSS configurations...
};

Make sure to include all relevant paths to your HTML and JavaScript files.

Step 3: Create a PurgeCSS Configuration File (Optional)

You can create a separate configuration file for PurgeCSS, though it's not mandatory. Create a purgecss.config.js file if you want more fine-grained control over the purging process:

// purgecss.config.js
module.exports = {
  content: ['./src/**/*.html', './src/**/*.js'],
  // Other PurgeCSS configurations...
};

Step 4: Run PurgeCSS

Add a script to your package.json to run PurgeCSS. This script can be part of your build process:

// package.json
{
  "scripts": {
    "build": "npm run purgecss && npm run build:css && npm run build:js",
    "purgecss": "purgecss --config purgecss.config.js --out dist/css/",
    "build:css": "your-css-build-command", // Replace with your actual CSS build command
    "build:js": "your-js-build-command"    // Replace with your actual JavaScript build command
  }
}

Adjust the your-css-build-command and your-js-build-command placeholders with your actual build commands for CSS and JavaScript.

Step 5: Run the Build Script

Execute the build script to run PurgeCSS and generate your optimized CSS output:

npm run build

By following these steps, you integrate PurgeCSS into your Tailwind CSS workflow, ensuring that only the necessary styles are included in your production build. This leads to a more streamlined and optimized CSS output, contributing to improved performance and faster loading times.

Deferred Loading of Tailwind CSS using <script> Tag:

If your Tailwind CSS file is large and not crucial for the initial rendering of the page, you can defer its loading using the async or defer attributes on the <script> tag. This strategy allows the browser to prioritize rendering the page content first, enhancing perceived performance. Below is an example using the defer attribute.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Your Page Title</title>
 <!-- Your other head elements go here -->

 <!-- Defer loading of Tailwind CSS -->
 <script defer>
   // Dynamically create a link element for Tailwind CSS
   const tailwindCSS = document.createElement('link');
   tailwindCSS.rel = 'stylesheet';
   tailwindCSS.href = 'Replace with your CDN link';
   const head=document.head;
   head.appendChild(tailwindCSS);
 </script>
</head>
<body>
 <!-- Your HTML content goes here -->

 <!-- Your other body elements go here -->
</body>
</html>

In this example, the Tailwind CSS file is loaded asynchronously after the page has been parsed. This approach improves the perceived performance because it allows the browser to render the page content without waiting for the CSS file to be fully downloaded and applied.

Choose between async and defer based on your specific requirements. async will start downloading the file immediately but may not maintain order, while defer ensures that the scripts are executed in order after parsing is complete.

Logo
Our team is creating and sharing useful resources on a regular basis and thousands of developers are using Tailwind CSS to create amazing websites with TailwindTap s free open-source pre-made components and templates.

Hire a Developers

TailwindTap FacebookTailwindTap TwitterLinkedinInstagram