§Two Ways to Artificially Boost CSS Specificity
Published on
Sometimes a selector needs more specificity(opens in new tab) to win against another rule. Maybe we’re overriding a third-party stylesheet, or a utility needs to beat a more specific selector without reworking the existing styles.
The first instinct is usually to add context to the selector, but that couples it to the markup structure:
.Target {} /* 0-1-0 */
div.Target {} /* 0-1-1 */
.Parent .Target {} /* 0-2-0 */There are two ways to boost specificity without introducing that coupling.
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 */Neither technique is self-evident, so they can be confusing if used without explanation. Use them only when there’s no better option, and always leave a comment explaining why.
Note: You can use this Specificity Calculator(opens in new tab) to easily determine a selector’s specificity weight.