While browsing some CSS code today I found some weird-looking declarations with duplicated selectors. For example:
.s-card.s-card {
box-shadow: 0 1px 3px hsla(0,0%,0%,0.06);
}
Initially, I thought it was a mistake but it seems that duplicating selectors is a perfectly valid way to increase the CSS specificity.
Let's say we have this HTML:
<div id="foo" class="bar"></div>
And this initial CSS rule:
#foo.bar { background-color: red; }
/* Specificity: 110
110 = 100(#foo) + 10(.bar) */
If we want to override this rule, without changing the HTML, we can create some new rules with higher specificity by repeating one of the two #foo
or .bar
selectors:
#foo.bar.bar { background-color:blue; }
/* Specificity: 120
120 = 100(#foo) + 10(.bar) + 10(.bar) */
#foo#foo { background-color:green; }
/* Specificity: 200
200 = 100(#foo) + 100(#foo) */
Some other ways to easily increase the specificity may include:
1. using the attribute selector
Using the attribute selector by specifying the attribute name inside square brackets ads a plus of 10 specificity points:
a { }
/* Specificity: 1
1 = 1(a) */
a[href] { }
/* Specificity: 11
11 = 1(a) + 10([href]) */
2. using the pseudo-classes
The pseudo-class has the same weight as a class selector, meaning 10 points. In the following example, the :has() selector will select only those h1 tags which have an a
tag inside them:
h1 { }
/* Specificity: 1
TOTAL 1 = 1(h1) */
h1:has(a) { }
/* Specificity: 11
11 = 1(h1) + 10(:has()) */
We can use some other pseudo-classes such as: :is(), :not() or :where().
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.