Programmatically set CSS selector specificity
Asked Answered
O

1

2

Is it possible to set the specificity of a CSS selector, as opposed to it only being determined by counts of the selector(s) comprising it? i.e., if I have two selectors like so (showing the calculated specificity):

UL OL LI        /* a=0 b=0 c=3 -> specificity =   3 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */

(examples from https://www.w3.org/TR/selectors/#specificity)

Is there any way to change the first example to this, in order to equalize the specificity of the two selectors and without adding an arbitrary class selector to do so:

UL OL LI        /* a=0 b=1 c=3 -> specificity =   13 */

-or-

UL OL LI.red    /* a=0 b=0 c=3 -> specificity =  3 */
Overshoot answered 27/5, 2017 at 16:14 Comment(0)
S
2

The specificity of a selector is determined solely by its component simple selectors (and pseudo-element, if any). You cannot change the specificity of a selector without altering the selector itself.

If you're worried about changing the meaning of a selector (or its set of potential matches), there are certain dummy simple selectors that you can add while keeping the semantics intact. In your example, you can increase the specificity of UL OL LI to match UL OL LI.red without actually taking a dependency on an arbitrary class name by either adding an unqualified :root to the beginning of the selector (with a descendant combinator) or adding :nth-child(n) to any one of the three type selectors — both are guaranteed matches, and pseudo-classes are equally specific to class selectors.

Also see my answers to the following questions for more options:

There is no similar way to decrease selector specificity, however, neither programmatically nor by altering the selector (except of course by removing redundant selectors like the aforementioned unqualified :root, :nth-child(n), or repeated type/class selectors).

Sully answered 27/5, 2017 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.