Search code examples
csscss-selectorscss-specificity

CSS specificity of comma-separated group selector


What is the proper way of computing the specificity for comma-separated group selectors?

The specificity for the following selector, for example, is 0,1,2,2 (1 for head, 1 for a, 10 for .left, 10 for :hover, and 100 for #title):

head #title .left a:hover

What would be the specificity for this selector? Would it also be 0,1,2,2? Or is this treated as multiple selectors, and a specificity has to be computed for each?

head,#title,.left,a:hover

Solution

  • In your first example you have ONE selector. It is a selector comprised of multiple simple selectors separated by descendant combinators. But it is still one selector.

    In your second example you have FOUR selectors. The comma separates selectors.

    §5. Groups of selectors

    A comma-separated list of selectors represents the union of all elements selected by each of the individual selectors in the list.

    For example, in CSS when several selectors share the same declarations, they may be grouped into a comma-separated list.

    Specificity applies to a single selector, so in your second example, which represents four distinct selectors, you need to calculate the specificity for each one separately.

    Think about it this way:

    The purpose of specificity is to establish which CSS rule gets applied to an HTML element when there are multiple selectors targeting the same element.

    .intro {
      border: 2px dashed red;
    }
    
    div {
      border: 1px solid black;
    }
    <div class="intro">text</div>

    Both selectors above are targeting the same element. A class selector has more specificity than a type selector (10 v 1), so the class wins.

    On the other hand, a comma-separated list of selectors applies the same rule to different elements, so specificity is not an issue.

    You don't normally do this:

    div, .intro {
      border: 1px solid black;
    }
    <div class="intro">text</div>

    ... because it's redundant.

    Comma separation is meant to consolidate selectors like this:

    h1, h2, h3 {
      color: red;
    }
    <h1>text</h1>
    <h2>text</h2>
    <h3>text</h3>

    ... which has nothing to do with specificity.