0
0
CssHow-ToBeginner · 3 min read

How to Use :not() Selector in CSS for Excluding Elements

The CSS :not() selector lets you select elements that do not match a given selector inside the parentheses. Use it like selector:not(selectorToExclude) to apply styles to all matching elements except the excluded ones.
📐

Syntax

The :not() selector takes a simple selector inside the parentheses and matches elements that do not match it.

  • selector: The elements you want to select.
  • :not(selectorToExclude): Excludes elements matching selectorToExclude.
css
selector:not(selectorToExclude) {
  /* styles here */
}
💻

Example

This example colors all list items except those with the class exclude in red.

css
ul li:not(.exclude) {
  color: red;
}

/* HTML for testing */

<ul>
  <li>Item 1</li>
  <li class="exclude">Item 2 (excluded)</li>
  <li>Item 3</li>
  <li class="exclude">Item 4 (excluded)</li>
  <li>Item 5</li>
</ul>
Output
A bulleted list where items 1, 3, and 5 are red, and items 2 and 4 remain default color (black).
⚠️

Common Pitfalls

One common mistake is putting complex selectors inside :not(), which only accepts a simple selector (like a class, id, or element). Also, forgetting that :not() excludes elements matching the selector inside it, so styles won't apply to those.

Example of wrong and right usage:

css
/* Wrong: complex selector inside :not() - this won't work as expected */
div:not(.class1.class2) {
  color: blue;
}

/* Right: simple selector inside :not() */
div:not(.class1) {
  color: blue;
}
📊

Quick Reference

  • :not(selector) excludes elements matching selector.
  • Use simple selectors inside :not() (class, id, element, attribute).
  • Combine with other selectors for precise styling.
  • Supported in all modern browsers.

Key Takeaways

Use :not() to style elements except those matching a selector.
:not() accepts only simple selectors inside the parentheses.
Combine :not() with other selectors for flexible styling.
Remember excluded elements inside :not() won’t get the styles.
Works in all modern browsers without extra setup.