What is the most common way to increase CSS specificity?

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

(This may seem like a trivial problem, but during my style sheets defining a sensitive grid, decreasing the specificity prefix with one character can save several hundred bytes)

+7
optimization html css css-selectors css-specificity
source share
2 answers

It really depends on what you are trying to achieve. A cheap way to increase specificity is to simply repeat the selector. For example, if this was your markup:

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

And that was your CSS:

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

You can simply repeat the class or id selector without changing your markup at all:

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

JSFiddle demo .

This is completely true, as the recommendations of W3C Selectors Level 3 in the section Calculating Specificity :

Note. Duplicate entries of the same simple selector are allowed and increase specificity.

+18
source share

Least bytes, but how much more specific?

It seems to me that for selectors, in most cases you cannot get less than two characters plus a space, especially if we are talking about the "global" use of adding specificity (which seems to be the case since you used html ). Therefore, to save CSS, you need one id symbol per html . I would say id (not a class), since you would like to keep it unique. So you implement the same in html:

 <html id="A"> 

Which then allows the shortest possible addition of a selector to CSS:

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

Then, using what James Donnelly said (which, incidentally, I never knew about repeating the same selector), you could constantly add more and more specificity with the least number of characters, for example:

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

Renouncement

Answering my questions, I do not recommend that this is necessarily a good way to make CSS, as well as a good way to deal with specific issues. But I believe that adding a short identifier for one character to the html element is the least number of bytes that could be used to increase the specificity of any selector that answers this question here.

+6
source share

All Articles