DEV Community

Ben Read
Ben Read

Posted on • Updated on

How to scope Tailwind CSS

I have a React app that uses Tailwind that gets embedded into a PHP app which also uses Tailwind. For that reason, I have two different builds of Tailwind that get injected into one page.

You probably don't want to do this. But in my case it was unavoidable: the React app and the PHP app are totally separate. The React app gets injected into several different PHP projects to provide extra functionality that they don't provide, but it's also a fairly complex form that needs to fit in to the UI of my company and also look like it's part of the parent application.

Both have a compilation step that is exclusive, so I could use the parent app's Tailwind CSS for some components, but I couldn't guarantee it will always contain what I need.

Didn't work: prefixing Tailwind classes

Tailwind itself provides a useful prefix utility that you would think scopes all of it's classes for you. However it doesn't do that. It's very useful if you're using Tailwind classes as well as other classes (say for separate JavaScript functionality).

Didn't work: Removing "preflight"

Tailwind also has a sort of CSS reset which you can also leave out of your builds. Whilst this is very useful to know about, I still got leakage, plus some of my UI elements looked awful without it.

Worked: Using css layers

In my main CSS file I wrapped a CSS layer around my Tailwind imports:

@layer myapp;

@layer myapp {
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

This worked. I was no longer seeing any styles removed in my parent application.

A few times I had to use an !important declaration to trump the reset, but that was fairly minor tradeoff and I think in the end I only used it on two classes.

<button class="!bg-sky-600 tw-m-2 !tw-p-2">
Enter fullscreen mode Exit fullscreen mode

Horrible but tolerable.

Hope this is helpful to someone!

Top comments (0)