:not() selector

Using the alphabet to play with :not()

":not() is a CSS negation pseudo-class selector. It is a functional pseudo-class selector that takes a simple selector as an argument, and then matches one or more elements that are not represented by the argument." -MDN

The :not() selector may be one of the least used css selectors, however, knowing when and how to use it can save a lot of time. :not() can be used with any regular selector such as

  • Type selectors (e.g p, button, pre)

  • Class selectors (e.g .header, .footer, .nav)

  • ID selector (e.g #logo)

  • Pseudo-class selectors (e.g :checked, :active)

  • Attribute selector (e.g :[type="submit"])

To use the :not() you pass an argument to the selector. The :not() will then apply the styling rules to all the elements except for the selector in its argument.

:not(selector) {
 css declarations;
}
li:not(.active) {
  /* will  style all list items except the list item with the class active */
}

The :not() is not without it's caveats. The argument passed to :not() cannot, be a pseudo-element (eg as :first-line and :first-letter etc).

You may have noticed that you can apply :not() with a pseudo-class but not a pseudo-element. For information on the difference between psuedo-classes and psuedo-elements click here

It is also possible to chain:not() selector with other :not() selectors. E.g. the following will match all articles except the one with a class of active, and then will filter out the list item that is the last item.

li:not(.active):not(:last-of-type) {
  /* style list items that are not active or last */
}

Alphabet & :not()

As mentioned before, the :not() selector matches the element that is not represented by the selector in its argument. We can use the alphabet to illustrate the power of the :not(). Consider the following

  • a
  • b
  • c
  • d
  • e
  • f
  • g
  • h
  • i
  • j
  • k
  • l
  • m
  • n
  • o
  • p
  • q
  • r
  • s
  • t
  • u
  • v
  • y
  • x
  • y
  • z

Now let's say you want to show only the vowels. You can achieve this by adding vowel class to each vowel in the list of letters. :not() selector will check against this class before styling the letters.

.alphabet > li:not(.vowel) {
  display: none;
}
  • a
  • b
  • c
  • d
  • e
  • f
  • g
  • h
  • i
  • j
  • k
  • l
  • m
  • n
  • o
  • p
  • q
  • r
  • s
  • t
  • u
  • v
  • y
  • x
  • y
  • z

You can only us :not() to change the background-color for vowels only.

.alphabet-test > li {
      background-color: $nav-link-color;
      &:not(.vowel) {
      background-color: grey;
      color: $body-color;
    }
  }
  • a
  • b
  • c
  • d
  • e
  • f
  • g
  • h
  • i
  • j
  • k
  • l
  • m
  • n
  • o
  • p
  • q
  • r
  • s
  • t
  • u
  • v
  • y
  • x
  • y
  • z

You can play with the code here Here