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

后端 未结 3 1450
北海茫月
北海茫月 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:

    <figure id="myId" class="myClass"></figure>
    

    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.

    0 讨论(0)
  • 2020-12-15 08:37

    Least Bytes, but How Much More Specific?

    It seems to me for selectors, in most cases you cannot get any shorter than two characters plus the space, especially if we are talking about a "global" use of adding specificity (which seems to be the case since you were using html). So to save on CSS, you need a single character id on the html. I would say an id (and not a class), as you would want to keep it unique. So you implement like so in the html:

    <html id="A">
    

    Which then allows for the shortest possible selector addition in the CSS of:

    #A .whateverYour [OriginalSelector] string .was {}
    

    Then using what James Donnelly stated (which, by the way, I never knew about the repetition of the same selector), you could continually add more and more specificity with the least amount of characters like so:

    #A#A#A .whateverYour [OriginalSelector] string .was {}
    

    Disclaimer

    By answering as I have, I am not recommending this is necessarily a good way to do CSS, nor a good way to handle specificity issues. But I do believe that adding the short one character id to the html element is the least amount of bytes one could use to increase specificity of any selector, which answers the question here.

    0 讨论(0)
  • 2020-12-15 08:56

    I've seen a postcss library use :not(#\9) which is pretty short, increases specificity by one, and basically works on everything. Doesn't work with ie8 or less, but come on this is 2020

    0 讨论(0)
提交回复
热议问题