Ask A Question

Notifications

You’re not receiving notifications from this thread.

What is the best way to add a dynamic active class to a link with Tailwind CSS?

spacerobotTR asked in CSS

From what I understand the "active variant" is not enabled by default? Where exactly do you enable that with rails? Is there another way to add and remove parts of classes to put together an active link depending on where you are in a rails site?

Any info is appreciated!

Reply

I either do it inline or in a helper.

Here's an inline example:

<%= link_to "Account", account_path, class: ["blue", ("active" if request.path == account_path)]
Reply

Ahhh yes that worked. Thanks!

Reply

Do you have to enable the active classes in Tailwind or are they there by default now? I didn't see a tailwind.js file only the postcss config. Is that where you would declare variants for tailwind?

Reply

You either need to define it or just have it add the classes you want to the list. "Active" means very different things depending on your UI design.

Reply

Thanks for the info! I was going by this video where he said the "active" variants were turned off by default to save space. I can create custom classes though.

https://tailwindcss.com/course/hover-focus-and-active-styles/

Reply

Ah sorry I was confused. I was thinking of the "active" state of a link / tab / etc.

He's referring to active like the &:active { css selector.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.