The Powerful CSS not Selector
March 28, 2022
•
––– views(Updated on April 23, 2022)
The :not() CSS selector is a powerful addition to the pseudo-class toolbelt, allowing you to select elements that are omitted by its argument.
Here’s an example. I have a few classes set up - one applies base styles for all buttons, one sets the styles of a primary button, and another determines what a primary disabled button should look like.
SCSS.button {border: none;padding: 1rem 2rem;border-radius: 0.5rem;cursor: pointer;margin-top: 1rem;}.button--primary {background: $button--primary;color: white;}.button--disabled {background: $button--disabled;cursor: auto;}
In order to align with accessibility, it’s important that the background of the button changes when in hover state. That’s simple enough; here’s the change.
SCSS.button--primary:hover {background: $button-primary-hover;}
But, after adding the :hover selector, we run into a problem. Try hovering over the disabled button and notice that the background changes as if we were hovering over an active primary button.
How do we get around this? The :not() selector makes this an easy fix, allowing the change to only affect primary buttons that are not disabled!
SCSS.button--primary:hover:not(.button--disabled) {background: $button-primary-hover;}
Thankfully, the :not() selector is supported by most major browsers.
Check out caniuse.com to see the exceptions.
In this article, we briefly discussed the :not() selector and saw a real-world example. A variety of options open up when using this selector - what applications can you think of?
Updates delivered to your inbox!
A periodic update about my life, recent blog posts, how-tos, and discoveries.
As a thank you, I'll also send you a Free CSS tutorial!
No spam - unsubscribe at any time!
- subscribers – - issues
More articles
If you enjoyed this article, you'll find these insightful too!