Difference between the :where() and :is() pseudo-classes?

Viewed 68

The :is() and :where() pseudo-class functions both take a selector list as an argument and select any element that can be selected by one of the selectors in that list. So how do they differ?

/* Selects any paragraph inside a header, main
   or footer element that is being hovered */
:is(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

/* Selects any paragraph inside a header, main
   or footer element that is being hovered */
:where(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

/* Both are equivalent to the following */
header p:hover,
main p:hover,
footer p:hover {
  color: red;
  cursor: pointer;
}
2 Answers

The difference between :where() and :is() is that :where() always has 0 specificity, whereas :is() takes on the specificity of the most specific selector in its arguments.

The pseudo-class :is() doesn't have any weight itself (unlike most pseudo-classes, which are the equivalent of classes in calculating specificity), but the values inside it's parentheses are used to calculate specificity instead. (By the way, it's the same case with another pseudo-class, :not().)

Example: div:where(.outer) p has a specificity score (ordered from highest to least specificity value: inline styling/style attribute, id, class/pseudo-class/attribute, element) of 0,0,0,2, while div:is(.outer) p is scored 0,0,1,2.

Here's a mnemonic: :is() is influential, :where() is worthless.

Source: MDN

Anything that :is() can do regarding grouping, so can :where() (including being used anywhere in the selector, nesting, and stacking them)

The difference is actually in specificity, that's the point which :is() and :where() strongly diverge.

:where() has no specificity (its specificity value is 0) and it squashes all the specificity in the selector list passed as functional parameters.

:is() takes the specificity of its most specific selector (it actually counts towards the specificity of the overall selector and takes the specificity of its most specific argument)

You can check out this great comparison : https://developer.mozilla.org/en-US/docs/Web/CSS/:where#examples

Related