Published on

How to Scope Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Scope Tailwind CSS

Tailwind CSS applies styles globally by default, which can sometimes cause conflicts in larger projects. Here are various ways to scope Tailwind to specific elements or components.

1. Using the important Option

The important option in tailwind.config.js allows you to scope all Tailwind styles to a specific class:

module.exports = {
  important: '.tailwind-scope',
}

Then, wrap your components inside a <div class="tailwind-scope"> to apply scoped styles.

2. Using Prefixes

You can add a prefix to all Tailwind classes to prevent conflicts:

module.exports = {
  prefix: 'tw-',
}

Now, instead of bg-blue-500, use tw-bg-blue-500.

3. Disabling Preflight (Global Reset)

If Tailwind’s global styles interfere with other styles, disable Preflight:

module.exports = {
  corePlugins: {
    preflight: false,
  },
}

This prevents Tailwind’s base styles from affecting global elements.

4. Using CSS Layers for Scoping

You can scope Tailwind styles within a custom CSS layer:

@layer custom-scope {
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
}

Then, apply styles within this scope using:

<div class="custom-scope">
  <p class="bg-blue-500">Scoped Tailwind</p>
</div>

5. Using PostCSS Nested Rules

For more controlled scoping, use PostCSS with nesting:

.scoped-tailwind {
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
}

Enable postcss-nested in postcss.config.js:

module.exports = {
  plugins: {
    'postcss-nested': {},
    tailwindcss: {},
    autoprefixer: {},
  },
}

FAQs

Why should I scope Tailwind CSS?

To prevent Tailwind styles from affecting global styles in an existing project.

Which method is best for scoping Tailwind?

  • Use important for quick scoping.
  • Use prefix if working in a shared environment.
  • Use CSS layers or PostCSS for more control.

Can I scope Tailwind in Next.js or Vue?

Yes, wrap Tailwind imports in a scoped container or use prefixes.