How to scope Tailwind CSS?



When using Tailwind CSS, the styles can apply to your whole website or app, which can cause issues if they affect areas you don't want. This happens because Tailwind's utility classes are global. So, how can you control where these styles are used?

In this article, we'll show you different ways to make sure Tailwind CSS only affects certain parts of your site, making it easier to manage and preventing unwanted changes.

Approaches to Scope Tailwind CSS

There are several methods you can use to limit Tailwind CSS styles to specific parts of your website or app, making your project easier to manage and avoiding unwanted global effects. These methods include:

Create Component-Specific Classes

In this approach, we aim to keep styles isolated by creating custom classes specific to components. Instead of directly applying Tailwind's utility classes in the HTML we group them into custom classes, making the code cleaner and more maintainable. Here's how we did it:

First, we install Tailwind CSS and its required dependencies:

npm install -D tailwindcss postcss autoprefixer

Next, we generate the Tailwind configuration file by running:

npx tailwindcss init

This creates the tailwind.config.js file. We configure this file as follows to ensure Tailwind scans our files:

// tailwind.config.js
module.exports = {
    content: ['./src/**/*.{html,js}'], // Ensure Tailwind scans all relevant files
    theme: {
        extend: {},
    },
    plugins: [],
};

We create a postcss.config.js file in the root of the project with the following content to ensure PostCSS works with Tailwind:

// postcss.config.js
module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
};

Now, we create a src/styles.css file to import Tailwind's base, components, and utilities. This is where we define our custom styles.

/* src/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Inside styles.css, we create a .button-primary class using the @apply directive to group Tailwind utility classes into a single custom class:

/* src/styles.css */
.button-primary {
    @apply px-6 py-3 bg-emerald-500 text-white rounded-2xl;
}

For example, let's create a .button-primary class to style a primary button. Rather than applying multiple utility classes in the HTML, we combine them into a single custom class.

Next, we create an HTML file (e.g., index.html) to test our scoped styles.

 <!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tailwind CSS Example</title> 
    <link rel="stylesheet" href="dist/styles.css">
</head>

<body>
    <button class="button-primary">Click Me</button>
</body>

</html>

In package.json, we add a build script to compile our Tailwind CSS. This script watches for changes and updates the output CSS file:

"scripts": {
    "build": "npx tailwindcss -i ./src/styles.css -o ./dist/styles.css --watch"
}

Finally, we run the following command to start the build process and watch for changes:

 npm run build

Output

output image

Use @apply for Custom Styles

In this approach, we aim to simplify our code and avoid repeating utility classes multiple times by using Tailwind's @apply directive.This allows us to group common utility classes into a single custom class by eliminating the need to repeat the same utility classes in multiple places. Here's hpw we did it.

Follow the same setup as in first approach for installing Tailwind, configuring tailwind.config.js, and postcss.config.js.

Now, instead of applying utility classes to each input field in the HTML, we'll use the .input-field class. In the src/styles.css file, add the following code:

/* src/styles.css */
.input-field {
    @apply border p-2 rounded-md border-blue-800 bg-purple-100;
}

Then, in our src/index.html, we update the input fields like this:

<!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Tailwind CSS Example</title> 
  <link rel="stylesheet" href="dist/styles.css">
</head>

<body>
  <input type="text" class="input-field" placeholder="Enter your text" />
  <input type="text" class="input-field" placeholder="Another input" />
</body>

</html>

We use the same build command in package.json as in our first approach.

After setting up the build script, run the following command to start the Tailwind build process:

npm run build

Output

Output Image approach2

Use PostCSS for Scoping

In this approach, we use PostCSS to add a custom prefix to all of Tailwind's utility classes, which prevents style conflicts with other global styles in the project.

First, we need to install PostCSS and the postcss-prefixer plugin to handle the prefixing of the Tailwind utility classes:

npm install postcss postcss-prefixer

After installing the required plugins, configure PostCSS by creating a postcss.config.js file. Add the following code:

// postcss.config.js
module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
        require('postcss-scoped')({
            prefix: '.component', // Adds a custom prefix for scoped styles
        }),
    ]
}

Next, we define our custom styles in src/styles.css, including Tailwind's @tailwind directives and using @apply for custom classes.

/* src/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

.button-primary {
    @apply px-6 py-3 border border-teal-700 bg-teal-500 text-white rounded-xl;
}

Now that we've set up the prefix, we can scope Tailwind styles by wrapping our components in a container with the .component class. Here's how we do it in the index.html file:

<!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tailwind CSS Scoped Example</title> 
    <link rel="stylesheet" href="dist/styles.css">
</head>

<body>
    <div class="component">
        <button class="button-primary">Click Me</button>
    </div>
</body>

</html>

We use the same build command in the package.json file as we did in the first approach.

Run the build command to generate the output CSS:

npm run build

Important Points: Make sure you have the correct version of postcss-scoped installed. You can check this by looking at your package.json or by running:

npm list postcss-scoped

If it's not installed, run:

npm install postcss-scoped

Output

Postcss output

Modify Tailwind Preflight Styles

In this approach, we modify Tailwind's Preflight styles to disable or customize them. Preflight applies default styles to common HTML elements, but we may need to prevent them from overriding our custom styles. Here's how we do it:

Follow the same steps as in the first approach for installing Tailwind, configuring tailwind.config.js, and setting up src/styles.css.

We create a new file named postcss.config.js in the root directory with the following content:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
    ],
};

We update the tailwind.config.js file to configure the content option and disable Preflight styles. Here's the code we add:

module.exports = {
    content: [
        './index.html',
        './src/**/*.{js,jsx,ts,tsx}',
    ],
    corePlugins: {
        preflight: false, // Disable Preflight styles
    },
};

In the package.json file, we add a build script under the scripts section:

"scripts": {
    "build": "npx postcss src/styles.css -o dist/styles.css"
}

We run the build command to generate the final CSS file. This will create the dist/styles.css file, which contains the processed Tailwind CSS styles:

npm run build

Than, we create an index.html file in the root directory of the project with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tailwind Preflight Disabled</title>
    <link rel="stylesheet" href="dist/styles.css">
</head>

<body>
    <p class="text-2xl font-bold">Hello, World!</p>
    <button class="bg-blue-500 text-white p-2">Click Me</button>
</body>

</html>

Now open the index.html file in a browser to see the output:

Output

output of approach

Use a CSS Class Prefix

In this approach, we can prevent conflicts between Tailwind's utility classes and other styles by adding a custom prefix to all Tailwind classes. This helps scope Tailwind's styles specifically to our project.

Follow the same setup as in the first approach for installing Tailwind and configuring tailwind.config.js and postcss.config.js.

After installing Tailwind, open the tailwind.config.js file and add a custom prefix to all Tailwind classes. For example, we'll use the prefix myapp-:

// tailwind.config.js
module.exports = {
    prefix: 'myapp-', // Prefix all Tailwind classes with 'myapp-'
    content: [
        './index.html', // Specify the files to purge unused styles
    ],
    theme: {
        extend: {},
    },
    plugins: [],
}

Create a styles.css file and add the Tailwind directives:

/* styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Next, compile the Tailwind CSSs by running the following command in the terminal:

npm run build

Now, you can use the prefixed classes (myapp-) in your HTML file. For example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Tailwind Project</title>
    <link href="output.css" rel="stylesheet" /> <!-- Link to compiled CSS -->
</head>

<body>
    <button class="myapp-bg-yellow-500 myapp-text-white 
                    myapp-px-4 myapp-py-3 myapp-rounded-xl 
                    myapp-button-primary">
        Click Me
    </button>
</body>

</html>

Finally, open the index.html file in your browser to see the output with the scoped Tailwind styles.

Output

output of prefix

Configure Tailwind's Purge Option

In this approach, we use Tailwind's purge option to remove unused styles in production. This helps reduce the CSS file size by ensuring only the classes used in your HTML or JavaScript files are included.

If you've already set up Tailwind (from the first approach), there's no need to repeat the setup. We will only update tailwind.config.js to enable purging.

Open tailwind.config.js and update it to specify where Tailwind should look for used classes:

    // tailwind.config.js
module.exports = {
  content: [
    './src/**/*.html', // Look for HTML files
    './src/**/*.js',   // Look for JS files
  ],
  theme: {
    extend: {},
  },
  corePlugins: {
    preflight: true, // Optional: Enable preflight styles
  },
}

Also make sure that your postcss.config.js file is configured correctly to use Tailwind CSS and Autoprefixer:

// postcss.config.js
module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
};

And update the index.html. Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tailwind Purge Example</title>
    <link href="./dist/styles.css" rel="stylesheet"> <!-- Final built CSS -->
</head>

<body class="bg-gray-100">
    <h1 class="text-2xl font-bold mb-4">Tailwind CSS with Purge</h1>
    <button class="bg-blue-500 text-white py-2 px-4 rounded">
        Click Me
    </button> 
</body>

</html>

Now to build the final CSS with purging enabled, run:

npm run build

Output

output purge
Updated on: 2024-12-31T09:22:40+05:30

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements