Explain Codes LogoExplain Codes Logo

:hover but :not on a specific class

css
responsive-design
best-practices
css-variables
Nikita BarsukovbyNikita Barsukov·Jan 14, 2025
TLDR

Implementing hover styles while excluding a certain class can be achieved using CSS :hover and :not() like so:

element:hover:not(.ignore-class) { /* hover styles */ }

This rule applies the hover style to all elements except those with .ignore-class.

Strategic hover effects

To apply hover effects without affecting a specific class, use :not(). It allows you to exclude elements containing that class from your hover style rules. Assume you have multiple menu items, from which the current active item should not get the hover effect:

li:not(.active):hover { background-color: #ff0; /* Turns non-active items into minions on hover 😄 */ }

The menu items with .active class won't change, keeping your active item distinct.

Cleaner code, improved readability

Putting :hover after :not() makes the intended interaction pattern more understandable:

a:not(.active):hover { color: blue; /* Blue-cifies non-active links on hover 😉 */ }

Unaffected by pseudo-class order

Functionality remains constant irrespective of the pseudo-class order. a:hover:not(.active) and a:not(.active):hover are identical. However, for backwards compatibility, to undo a:hover effect, if :not() isn't recognized, provide a fallback:

a.active:hover { color: initial; /* A life-saver when future tech hasn't reached all browsers */ }

Playing nice with older browsers

If you're seeking wider browser compatibility, cater for older versions by implementing specificity overrides:

a:hover { color: blue; /* Hover magic for everyone */ } a.active { color: red; /* Active link thinks it's cool to be different */ }

Diving deeper: leveraging hover interactions

Mastering hover sensitivity

For a more seamless interaction, consider the size and proximity of hoverable elements. Prevent unwanted hovers with :not() when elements are larger or closer together.

Switching classes with JavaScript

Dynamically remove hover styles by adding or removing classes using JavaScript:

document.querySelector('.my-element').classList.add('no-hover'); /* You're it, no hover for you */

Simplifying code with CSS Variables

Improve maintenance and flexibility of hover effects using CSS variables. They adjust effects without changing the basic hover structure:

element { --hover-effect: scale(1.2); /* Everything gets bigger, until... */ } element:hover { transform: var(--hover-effect); } element.no-hover { --hover-effect: none; /* ...someone decides to stay same size */ }