Fix TailwindCSS breaks existing styles
When you start using TailwindCSS in an existing project where some CSS styles have already been defined, you may be in for a nasty surprise.
Sometimes, even before you use a single Tailwind style, the existing design breaks.
There are two main reasons for this.
TailwindCSS preflight
The first is that TailwindCSS automatically generates a generic, opinion-based CSS normalization code so that everything appears the same in different browsers. In an existing project, there is probably already a basic CSS reset code. Depending on the CSS files import order the original reset code will be overwritten by the code generated by Tailwind.
For example, Tailwind automatically changes the value of the box-sizing
property to border-box
.
If you don't want Tailwind to generate its own reset code, you can fortunately disable this feature. To do this, use the preflight
configuration parameter.
In the tailwind configuration file tailwind.config.js
, set the preflight
value to false
in the corePlugins
block.
module.exports = {
content: ['**/*.html'],
theme: {
extend: {},
},
plugins: [],
corePlugins: {
preflight: false,
}
}
Class name conflicts
The second reason for breaking the old design can be the CSS class name conflict. For example, if you use Bootstrap, there is a p-2
class, and TailwindCSS also has one. Since they set different padding
values - depending on the import order - one will overwrite the other and can again cause design problems.
To eliminate this type of problem, you can prefix Tailwind classes. So, for example, instead of class p-2
, you use class tw-p-2
.
The prefix can be specified in the tailwind configuration file using the self-explanatory prefix
property. Of course, the value of the prefix property can be anything the tw-
value is just a general convention.
module.exports = {
prefix: 'tw-',
content: ['**/*.html'],
theme: {
extend: {},
},
plugins: [],
}
If you use the prefix option, don't forget to prefix the class names in your template files. So what used to look like this:
<div class="text-black text-4xl py-2">Lorem ipsum...</div>
will now look like this:
<div class="tw-text-black tw-text-4xl tw-py-2">Lorem ipsum...</div>