Subscribe

CSS :not selector for negation

✍️

Understanding how to not select an element in CSS is crucial. Learn in this Guide how to use the CSS not selector with examples.

30 Nov, 2020 · 2 min read

The CSS :not selector is really cool. We can call it a negation pseudo-class selector.

A mouth-full, but what it does, is it selects elements that do NOT match certain criteria.

The cool part is that it can be used on many types of elements.

  • Classes (.nav__item)
  • ID’s (#my-element)
  • Types (div, li, etc)
  • Pseudo-classes (:last-child)
  • Attributes ([type=“radio”])

Note: It doesn’t style CSS pseudo-elements so ::before won’t work nor can’t it style itself (:not(:not(...))).

Example HTML Structure

For this demo we will make a simple list which we will style with CSS and the not selector.

<ul>
  <li class="new">Text rule 1</li>
  <li id="not_me">Text rule 2</li>
  <li>Text rule 3</li>
  <li>Text rule 4</li>
  <li>Text rule 5</li>
</ul>

CSS :not selector

Match any HTML element but the last child:

li:not(:last-child) {
  color: purple;
}

This will result in the following styling:

CSS selector not last-child

Match every element but not one ID:

li:not(#not_me) {
  color: red;
}

CSS selector :not #id

Don’t match a class with the negation selector:

li:not(.new) {
  color: blue;
}

CSS :not class

I hope these code examples give you a good overview of just how powerful the :not selector in CSS can be for your website.

It might really save you from having some weird CSS classes just to exclude one item from styling.

View the demo examples in this Codepen

See the Pen Not selector in CSS3 by Chris Bongers (@rebelchris) on CodePen.

Browser Support of the CSS3 selector :not

The :not selector has really good browser support, just some issues on Android and Opera mini (where the later just doesn’t support about anything).

CSS3 :not browser support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Modifying an SVG path with CSS

10 Dec, 2022 · 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 · 2 min read

Animate an SVG path with CSS

Join 2097 devs and subscribe to my newsletter