CSS :not() Pseudo Class

CSS :not() Pseudo Class

CSS :not() Pseudo-Class

The :not() pseudo-class allows you to exclude elements that match a specific selector. It’s useful when you want to style everything except certain elements.

1. Syntax

selector:not(condition) { /* Styles for elements that DO NOT match the condition */ }

✅ The :not() function takes one simple selector (not a full selector chain).

2. Example – Exclude a Specific Element

<ul> <li>Item 1</li> <li class="exclude">Item 2 (excluded)</li> <li>Item 3</li> <li>Item 4</li> </ul>
li:not(.exclude) { color: green; }

All <li> elements EXCEPT .exclude turn green.

3. Excluding Multiple Elements

p:not(.important, .highlight) { color: gray; }

✅ All <p> elements except those with .important or .highlight turn gray.

4. Combining :not() with Other Selectors

Exclude the Last Child

li:not(:last-child) { border-bottom: 1px solid black; }

✅ Adds a bottom border to all <li> except the last one.

Exclude Disabled Inputs

input:not(:disabled) { background-color: lightyellow; }

✅ Only enabled inputs get a light yellow background.

Target Everything Except div

*:not(div) { margin: 10px; }

Every element except <div> gets margin: 10px.

5. :not() with Multiple Conditions

p:not(:first-child, .special) { font-style: italic; }

✅ Styles all <p> elements except:
✔ The first child
✔ Elements with .special class

6. :not() vs. :has() (Upcoming Feature)

  • :not() excludes elements matching a condition.

  • :has() (not widely supported yet) selects elements that contain certain children.

7. Browser Support

Fully supported in Chrome, Edge, Firefox, Safari, and Opera.

8. Best Practices

✔ Use :not() for exclusion instead of writing complex selectors.
✔ Combine it with pseudo-classes (:last-child, :nth-child(), etc.).
✔ Avoid overly complex :not() rules to maintain readability.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close