While the accepted answer is accurate, using the !important
rule for Tailwind classes may not always be the best approach. Placing !important
on true
can potentially cause conflicts when integrating third-party JS libraries that apply inline styles to your elements. In such scenarios, Tailwind’s !important
utilities can override the inline styles and disrupt your intended design.
To work around this issue, you can set !important
to an ID selector like #app
:
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
// ...
important: '#app',
}
By prefixing all utilities with the specified selector, their specificity will be enhanced without necessitating them to be marked as !important
.
Once you have configured the selector in your tailwind.config.js
file, ensure that the root element of your website matches it. For example, if you use #app
, the root element's id
attribute must also be set to app
for the styles to function correctly.
With the setup complete and the root element aligned with the config selector, Tailwind’s utilities will possess enough specificity to override other classes in your project, without interfering with inline styles:
<html>
<!-- ... -->
<style>
.high-specificity .nested .selector {
color: blue;
}
</style>
<body id="app">
<div class="high-specificity">
<div class="nested">
<!-- Will be red-500 -->
<div class="selector text-red-500"><!-- ... --></div>
</div>
</div>
<!-- Will be #bada55 -->
<div class="text-red-500" style="color: #bada55;"><!-- ... --></div>
</body>
</html>
Important modifier
Alternatively, you can make any utility important by adding a !
character at the beginning:
<p class="!font-medium font-bold">
This will be medium even though bold comes later in the CSS.
</p>
This technique can prove valuable in rare situations where increased specificity is required due to conflicts with external styles beyond your control.