I’m writing a WordPress plugin using ReactPress as well as Tailwind and don’t want the part of my application’s CSS that is written in React to affect the styles of the WordPress part.
However, since
index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
is applied to the whole page, this screws up the rest of the page.
Is there any way to only make these styles apply inside a certain element, like this for example?
div#root {
@tailwind base;
@tailwind components;
@tailwind utilities;
}
2
Answers
There is no way to configure nesting or scoping tailwind styles to only a container with
@tailwind base; @tailwind components; @tailwind utilities;
directly.Optimal Embedded / Nested Tailwind Configuration
You can alter the
tailwind.config.js
configuration and add a CSS Reset stylesheet to achieve an optimal "embedded" tailwind solution.You can create a classic CSS Reset set of styles on a container where you want to cancel out the styles of the parent website or application. Where everything is prefixed with the container class you want to have styles reset on, so that the tailwind styles can be appropriately applied below this container.
Example CSS reset docs:
Example
embed-reset.css
partial example
Example
tailwind.config.js
Notice:
Example
main.tsx
React AppNotice the
embed-reset.css
comes before theindex.css
.Parent Website / Application
You will need a
<div>
with the idreact-embed-1
and the classreact-style-reset
in your parent app for this example:Your parent app can load your react app’s generated .js bundle and .css file on the page with the above div for the react app to appear with proper tailwind styles.
For example, if you are using vite + tailwind to generate these files, the build output index.html would include example tags for the script and stylesheet.
Refer to this:
https://www.npmjs.com/package/tailwindcss-scoped-preflight
This lets you define
isolationStrategy
, where you can pace a single selector or an array of selectors(inside your tailwind.config.js):This will apply it to all of the containers using the class
tw-class
, theid tw-id
and its children.A really smooth solution!