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

一世执手 提交于 2019-11-28 23:39:34

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.

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.

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