How to give hover class less precedence in TailwindCSS

Viewed 87

I'm new to Tailwind, and I'm not sure if there's a way to solve this edge case. Here is the scenario:

We have different variants listed on the product page(for example different color tags). When you hover we are showing a faded border around the tag, and when you select the variant, the tag becomes active, and its border should get darker.

The problem: Even when the user clicks on the tag to make it active, the user still sees hover still rather than the 'active' style.

These are the classes I'm using for now

<Tag
clssName={`flex rounded border border-gray-200  bg-white hover:border-gray-400 ${active && 'border-gray-700'}`}
...prop
/>

Now the question is if there's a way to override the hover styles on when the item is active. One way could be to remove the hover class when the item is active, but I was wording if there is a Tailwind way to fix it.

3 Answers

You can add different styles for active and non-active variants.

<Tag
clssName={`flex rounded border bg-white ${active && 'border-gray-700 hover:border-black'}`} ${!active && "border-gray-200 hover:border-gray-400"}
...prop
/>

Well you can use focus utility for this.

Below is the example you can see where button has different behaviour on hover and focus.

<script src="https://cdn.tailwindcss.com"></script>
<div class="p-10">
  <button class="p-4 bg-pink-100  hover:bg-pink-300 focus:bg-red-500 focus:border-2 focus:border-red-700">Click </button>
  </div>

You can achieve this with a ternary operator on className. By default we have border-gray-200 hover:border-gray-400 when state changes, we replace border-gray-700 instead of border-gray-200 hover:border-gray-400.

const App = () => {
  const [active, setActive] = React.useState(false);
  return ( 
    <button onClick = {() => setActive(!active)}
    className={`flex p-3 rounded border bg-white ${active ? 'border-gray-700' : 'border-gray-200 hover:border-gray-400'}`
    }>
    {active ? 'Active' : 'Inactive'} 
    </button>
  );
};

const rootElement = document.getElementById('root');
ReactDOM.createRoot(rootElement).render( < App / > );
<script src="https://cdn.tailwindcss.com"></script>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root" class="p-10"></div>

Related