Programmatically set CSS selector specificity

对着背影说爱祢 提交于 2020-01-07 03:48:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!