Tailwindcss preflight and legacy code

Michał RomanMichał Roman
2 min read

Tailwindcss provides a set of base styles that help keep your pages consistent. These include removing margins, resetting font sizes and weights, unstyling lists, and many more. While this is helpful for new projects, it can be tricky to apply Tailwind to an older project that already works well and you don't want to reset everything.

Inside Tailwind's configuration file, tailwind.config.js, there's a section called corePlugins. Set preflight to false if you don't want Tailwind to reset all the styles. This option is useful if you prefer to manage the resets yourself or if you already have a set of base rules.

What if you have an old project and want to use the TailwindUI library of components, which assumes you're using Tailwind's reset? In this case, if you set preflight to false, all TailwindUI components will break and won't look good because they rely on the reset you just removed.

Recently, I found a very useful npm package that solves this issue. It makes Tailwind's preflight scoped to the class selector of your choice. This way, you control which components should have their styles reset, and it won't affect your legacy code.

The package is called tailwindcss-scoped-preflight and can be found here: https://www.npmjs.com/package/tailwindcss-scoped-preflight

Adding it to your project is simple. First, add this import inside your config file:

import { scopedPreflightStyles, isolateInsideOfContainer } from 'tailwindcss-scoped-preflight';

Then, inside the plugin's config, add this:

scopedPreflightStyles({
  isolationStrategy: isolateInsideOfContainer('.your-selector'),
});

And that's basically it. You can keep your legacy code unaffected by your new Tailwind components and vice versa. Just remember to place your new components inside a container with the class you configured.

0
Subscribe to my newsletter

Read articles from Michał Roman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Michał Roman
Michał Roman