I’m working on a project using Vite and React to build a widget that users can integrate into their websites. I’m using Tailwind CSS for styling and injecting the styles into the DOM using the vite-plugin-css-injected-by-js plugin. However, I’m facing issues where my widget styles are overriding the host page styles, and sometimes the host page styles are overriding my widget styles. Here’s apart of my current Vite configuration:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
react(),
tailwindcss(),
cssInjectedByJsPlugin({ styleId: 'widget-styles' }),
],
});
And here’s my index.css file:
@import 'tailwindcss' important;
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentColor);
}
}
@layer utilities {
/* Chrome, Safari and Opera */
.no-scrollbar::-webkit-scrollbar {
display: none;
}
.no-scrollbar {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
}
Questions: 1-How can I ensure that my widget’s Tailwind CSS styles do not override the host page styles?
2-How can I prevent the host page styles from overriding my widget’s styles?
Are there any best practices or Vite/Tailwind configurations I can use to isolate my widget’s styles effectively?
I’ve used the cssInjectedByJsPlugin to inject styles with a unique styleId.
I’ve added @import 'tailwindcss' important; to my index.css to increase specificity.
@utilityCSS-first directive instead of@layer utilities. See more here:@utilitydirective and Adding custom utilities from v4