Search code examples
tailwind-csscreate-react-appreact-app-rewired

Scope tailwind to a certain class / id


I am looking into a possibility to scope the resulted tailwind css. The project uses react-app-rewired.

I already using tailwindcss-scoped-preflight to scope the preflight styles to my app, but the computed classes do not get scoped.

Also prefixing apparently does not work. Using a class or id prefix (for example prefix: "#root ",) does lead to not emiting any tailwind classes at all.

Using scss also did not work. The framework just emited the css code like this:

#root {
  .m-0 {
    margin: 0px;
  }
  ...
}

But Can I use states only 80.68% fully suport for css nesting.. https://caniuse.com/css-nesting

The goal would be instead of creating the classes like this:

.m-0 {
  margin: 0px;
}
.m-2 {
  margin-bottom: 0.5rem;
}
...

to be created as this:

#root .m-0 {
  margin: 0px;
}
#root .m-2 {
  margin-bottom: 0.5rem;
}
...

Any ideas what i can do? Thank you all.


Solution

  • You could consider using the selector strategy of the important configuration:

    […] you can set important to an ID selector like #app instead:

    tailwind.config.js

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      // ...
      important: '#app',
    }
    

    This configuration will prefix all of your utilities with the given selector, effectively increasing their specificity without actually making them !important.

    This would mean utility grouped Tailwind classes will have this scoping "prefix":

    #app .m-0 {
      margin: 0px;
    }
    #app .m-2 {
      margin-bottom: 0.5rem;
    }
    

    tailwind.config = {
      important: '#root',
    };
    <script src="https://cdn.tailwindcss.com/3.4.3"></script>
    
    <div id="root">
      <div class="h-10 w-10 bg-red-200"></div>
    </div>
    
    <div class="h-10 w-10 bg-red-200"></div>

    Do be aware that base and component rules may not have this scoping prefix, so you would most likely need to keep using the tailwindcss-scoped-preflight package you mentioned.