Luciano Battagliero

Two Simple Techniques for Boosting CSS Selector Specificity

When writing CSS, there will be times when we need to define a selector in a less-than-ideal way, just to boost its specificity[1][2] weight.

Our first instinct might be to add context to the selector, but doing so can lead to unnecessary coupling with the markup structure:

.Target { /* 0-1-0 */ } 

div.Target { /* 0-1-1 */ }
.Parent .Target { /* 0-2-0 */ }

Instead, let’s consider these alternatives:

  • Duplicating the selector:
    .Target { /* 0-1-0 */ } 
    
    .Target.Target { /* 0-2-0 */ }
    .Target.Target.Target { /* 0-3-0 */ }
  • Using the :not() pseudo-class:
    .Target { /* 0-1-0 */ } 
    
    :not(.FakeClass) .Target { /* 0-2-0 */ }
    :not(#FakeId) .Target { /* 1-1-0 */ }

By using these techniques, we won’t couple the selector with the markup structure. However, these are “hacks”, so they don’t clearly convey intent. Use them only when there’s no better option, and always add a comment when you do!

Note: You can use this Specificity Calculator to easily determine a selector’s specificity weight.
Scroll buffer added for your convenience.