(Non-)Forgiving CSS Selectors
#26 · 2021-03-26 (updated 2021-05-02) · CSS, compatibilityCSS is non-forgiving with lists of selectors when a browser doesn't recognize a specific selector.
For example, using p, :non-standard { color: red }
will not change the color of any paragraph.
As :non-standard
is not a valid selector, the whole ruleset must be discarded.
a selector list containing an invalid selector is invalid.
— Source
Some members of the CSSWG agree that this is a mistake in the specification but cannot be changed because of backward-compatibility.
Selectors have terrible future-proofing. We should have split on top-level commas, and only ignored unknown/invalid segments, not the entire thing.
— Source
Luckily, that situation is about to improve as Selectors Level 4 (Draft) is introducing the concept of forgiving selector lists.
By using the :where
or :is
pseudo-classes, a list of selectors can be used as a forgiving selector list.
With the following code example, all compatible browsers would color paragraphs in red.
:where(p, :non-standard) { color: red }
[...] wrapping a style rule’s selector in
:is()
effectively "upgrades" it to become forgiving. The [forgiving selector list] parses each selector in the list individually, simply ignoring ones that fail to parse, so the remaining selectors can still be used.
— Source