How to add an active state in Tailwind CSS
1. using tailwindcss/plugin
- import
tailwindcss/plugin
tailwind.config.js
js -> const plugin = require('tailwindcss/plugin')
ts -> import plugin from 'tailwindcss/plugin';
- define
addVariant
active 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.js
like 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.