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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With