How To Encapsulate The Base Styles Of Tailwind CSS

No Comments
Published: 24.03.2024

Do you want to learn how to encapsulate the base styles and CSS reset of Tailwind CSS? This is required if you want to embed a widget into another website without changing the style of this site! To achieve it, we basically have to give an id to the root of the element and then prefix all the CSS classes with that id.

I used this approach inside my search widget (SearchItFast), which I described in more detail in this post here.

  1. Encapsulate the base styles (and CSS reset) of Tailwind CSS
  2. Use the prefixed base styles

Encapsulate the base styles (and CSS reset) of Tailwind CSS

Before we begin, we will add the plugin tailwindcss/nesting to our postcss.config.js. We will need it to use our ID prefix for the base styles:

export default {
  plugins: {
    'tailwindcss/nesting': {},
    tailwindcss: {},
    autoprefixer: {},
  },
}

Next, we will go to our app.css file (the one with our @tailwind directives) and only use @tailwind base. After we did that, we need to run pnpm build. We then need to copy the generated CSS and create a new CSS file called base.css. Inside the base.css file, we will create the prefix with #prefix and then add paste the base styles.

#prefix {
/* base styles */
}

Next, inside our tailwind.config.js, we set preflight to false to stop the generation of the base styles:

  corePlugins: {
    preflight: false,
  },

Finally, we update the app.css by importing the base.css file and using the other @tailwind directives:

Need help or want to share feedback? Join my discord community!

@import './base.css';
/* @tailwind base; */
@tailwind components;
@tailwind utilities;

Use the prefixed base styles

To now use the base styles we need to create an element inside of our widget with the id of prefix. Ideally, this should be the root element so that all children have the base styles applied. For example, we can have a div like this:

<div id="prefix">
    <!-- ... content -->
</div>

Conclusion

With that you learned how to encapsulate the base styles and CSS reset of Tailwind CSS using a prefix. I hope this quick guide was helpful to you! If you have any questions feel free to ask!

KOFI Logo

If this guide is helpful to you and you like what I do, please support me with a coffee!

And if you enjoyed this guide consider subscribing to my newsletter!

[convertkit form=2303042]

Sources:

  1. https://stackoverflow.com/a/69999793

Discussion (0)