Using Tailwind within non-Tailwind websites
Sometimes, you may want to use or create Tailwind components within an existing non-Tailwind website for prototyping, quickly launching a feature, or incrementally converting everything to Tailwind.
The fastest way I've discovered, without complex build processes, is to use the Play CDN with a custom scoped Preflight. It's ideal to use the important
option in the Tailwind config to ensure all your Tailwind styles are scoped and will override existing site styles. Also, make sure to disable the default preflight
option.
I am using .tw
for the important selector, and the custom Preflight will only target elements within the .tw
container using the :where() CSS pseudo-class function.
Add the Play CDN & custom Preflight to the <head>
tag
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
important: '.tw',
corePlugins: {
preflight: false,
}
}
</script>
<style>
/* Include Scoped Preflight CSS Here... */
</style>
scoped-preflight.css scoped-preflight.min.css
Add Tailwind components inside the scoped .tw
element
<section class="tw">
<h1 class="text-2xl font-semibold text-teal-600">
Tailwind Headline
</h1>
<p class="text-lg mt-2">
Tailwind lorem ipsum paragraph. Dolor sit amet.
</p>
</section>
You don't have to use the Tailwind Play CDN, but it's always my first step to ensure everything works correctly. Remember to remove the Play CDN and use the built CSS before going live.
Fighting the cascade
Even though we contained Tailwind's preflight and generated classes, it's still challenging to prevent external classes from interfering. Conflicts can arise if classes with the same name exist, such as Bootstrap's utility classes, which have similar names to Tailwind's.
When an existing class has a property with the !important
flag and shares the same name as a Tailwind class, the Tailwind class won't overwrite the existing styles. This often happens with Bootstrap's utility classes. The simplest way to resolve this is by using Tailwind's important rule (e.g., !mb-4
).
If there are other classes with the same name but different properties, you can add to the custom preflight to revert those styles. For example, both Bootstrap and Tailwind use the .container
class.
:where(.tw) .container {
all: revert;
}