The not() Selector and Negation

What :not() Does

:not() matches an element only when it does not match whatever selector is passed inside it - effectively negating a selector.

button:not(.disabled) {
  cursor: pointer;
}

This targets every button except those carrying the disabled class.

A Common Use: Excluding the First or Last Item

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

Combining :not() with a structural pseudo-class like :last-child is one of the most common patterns for adding dividers between list items without an extra rule to remove the divider from the final one.

Multiple Selectors Inside :not()

input:not([type="checkbox"], [type="radio"]) {
  border: 1px solid #ccc;
}

Modern CSS allows a comma-separated list inside :not(), matching anything that fails to match any of the listed selectors - here, every input except checkboxes and radio buttons.

How :not() Relates to :is()

:not() and :is() are opposites: :is() matches if any listed selector matches, while :not() matches if none of them do. Together they cover most cases where a selector needs to describe "any of these" or "none of these" conditions.

A Specificity Note

Unlike :where(), :not() takes on the specificity of whatever selector is inside it - a rule using :not(#header) carries the specificity weight of an ID selector, even though it is excluding that ID rather than matching it.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.