Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 like a trivial issue, but over the course of my stylesheets defining a responsive grid, decreasing the specificity prefix by a single character would save a few hundred bytes)

like image 770
wheresrhys Avatar asked Oct 16 '13 09:10

wheresrhys


People also ask

How do you increase specificity in CSS?

As a special case for increasing specificity, you can duplicate weights from the CLASS or ID columns. Duplicating id, class, pseudo-class or attribute selectors within a compound selector will increase specificity when overriding very specific selectors over which you have no control.

Which CSS selector adds the highest level of specificity?

ID selectors have the highest specificity amongst the CSS selectors: 1, 0, 0, 0. Because of the unique nature of the ID attribute definition, we are usually styling a really specific element when we call up the ID in our CSS. – The specificity is 1, 0, 0, 1 because we have a type selector and an ID selector.

Which of the following has the highest CSS specificity?

Inline styles have the highest specificity. In our specificity weight system, they have a value of 1000. Let's try to make sense of it. The property values of selectors with a higher weight will always be applied over a selector with a lower weight.

Which of the following two selectors has a higher CSS specificity?

ID selectors have a higher specificity than attribute selectors. You should always try to use IDs to increase the specificity. A class selector beats any number of element selectors. The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.


1 Answers

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.

like image 152
James Donnelly Avatar answered Sep 19 '22 08:09

James Donnelly