问题
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 */
回答1:
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:
- Can type selectors be repeated to increase specificity?
- CSS class repetition to increase specificity
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).
来源:https://stackoverflow.com/questions/44219057/programmatically-set-css-selector-specificity