:hover but :not on a specific class
Implementing hover styles while excluding a certain class can be achieved using CSS :hover
and :not()
like so:
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:
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:
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:
Playing nice with older browsers
If you're seeking wider browser compatibility, cater for older versions by implementing specificity overrides:
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:
Simplifying code with CSS Variables
Improve maintenance and flexibility of hover effects using CSS variables. They adjust effects without changing the basic hover structure:
Was this article helpful?