Question

Which class selector rules have a higher specificity for 10 marks?

.A.E.F .C .D

OR

.A .B .C span

HTML:

<div class="A E F">
    <div class="B">
        <div class="C">
            <div class="D">
                <span>17590</span>
                <span>Points</span>
            </div>
        </div>
    </div>
</div>

CSS:

.A.E.F .C .D /* span */ {
    font-size: 1em;
}

.A .B .C span {
    font-size: .95em;
}

Here is a JS fiddle demonstrating the issue: http://jsfiddle.net/UgkZY/

I would have thought that the first rule would win. 5 x classes as opposed to 3 x classes + 1 x type. However, the second rule wins out as the .A.E.F appears to only score as 1 class.

If I use the following on-line CSS specificity calculator, http://specificity.keegan.st/, it thinks that the first rule is going to win. In reality, in the Chrome browser, the second one wins.

Can someone clarify that .A.B.C is indeed considered just one class in terms of CSS specificity?

BTW, if I add a span selector to the first rule it will win out.

According to the CSS specification to me it looks like the first one should win.

http://www.w3.org/TR/selectors/#specificity

LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */

Very confusing I must say.

Was it helpful?

Solution

Specificity is only relevant when comparing selectors that match the same element. In this case, your two rules match totally different elements: the first rule matches a div element that contains a class D (div.D), while the second rule matches span elements inside that div.D. What happens then is that both rules apply, but to different elements, resulting in the font size of the span being 95% of that of div.D, which in turn is 100% that of its ancestors. No overruling or overriding of styles takes place.

If you add span to the first rule, this causes it to match the same span elements inside div.D that the second rule also applies to. Only then does specificity come into play: the first rule ends up overriding the second based on counting the class selectors.

Also, .A.B.C counts as three classes; each class selector counts for itself.

OTHER TIPS

Indeed, the second selector wins. It's probably because .A.E.F targets a single element in the HTML tree.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top