Active state in Tailwind CSS
Some ways how to add an active state in Tailwind
1. Using tailwindcss/plugin
- import
tailwindcss/plugin
tailwind.config.js
js -> const plugin = require('tailwindcss/plugin')
ts -> import plugin from 'tailwindcss/plugin';
- define
addVariantactive inplugins:[]
plugins: [
plugin(function({ addVariant }) {
addVariant('current', '&.active');
})
],
- then use it on HTML like this
[&.active]:
<li class="[&.active]:bg-red-200">menu</li>
2. Using data-active="true"
- Add a
data-active="true"to the with your logic. - Then you may apply classes without needing to modify your plugins in your
tailwind.config.jslike so:<a data-active="true" href="#" class="data-[active=true]:bg-red-200"> - This is the active class name from above to modify the background color:
data-[active=true]:bg-red-200
^ This is how the Next.js <Link></Link> adds active state to menu links.