What is the most character-efficient way to increase CSS specificity?

后端 未结 3 1533
北海茫月
北海茫月 2020-12-15 07:59

If I want to increase the CSS specificity of a rule, I tend to prefix with html, but I wonder if there are more concise ways of doing this?

(It may seem

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 08:33

    This really depends on what you're trying to achieve. A cheap way of increasing specificity is to simply repeat a selector. For instance, if this was your markup:

    And this was your CSS:

    #myId.myClass { color:red; font-weight:bold; }      /* Specificity: 110 */
    

    You could simply repeat the class or id selector without modifying your markup at all:

    #myId.myClass.myClass { color:green; }              /* Specificity: 120 */
    #myId#myId { font-weight:normal; }                  /* Specificity: 200 */
    

    JSFiddle demo.

    This is completely valid, as the W3C Selectors Level 3 Recommendation states in its Calculating Specificity section:

    Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.

提交回复
热议问题