1

I have two competing rules in my stylesheet:

#parent > div {
    color: blue;
}

#child {
    color: red;
}

Here's the relevant HTML:

<div id="parent">
 <div id="child">What color is this text?</div>
 <div>This should just be blue</div>
 <div>Also should be blue</div>
</div>

Why is #child blue and not red?

I'm not sure if I'm applying the scoring system correctly. Here's how I did it:

  • rule #1 has an id and a tag, so its score is [0, 1, 0, 1]
  • rule #2 has only an id, so its score is [0, 1, 0, 0]
  • therefore rule #1 wins, and it's blue

But this seems wrong to me -- the first rule matches multiple elements; the second rule can only match one! So isn't the second rule more specific?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192

1 Answers1

2

But this seems wrong to me -- the first rule matches multiple elements; the second rule can only match one! So isn't the second rule more specific?

Not at all. Just because a selector matches fewer elements doesn't make it more specific.

Selector matching is done on a by-element basis, not a by-rule basis. Since there's a more specific selector that matches your element #child, which is #parent > div, that rule takes precedence, and that's it.

It does seem counter-intuitive, but that's just how it works. One way around this is to add #parent to your second rule:

#parent > div {
    color: blue;
}

#parent > #child {
    color: red;
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • You could also think of it this way: rule #1 applies to `div` elements only if they are children of any element with the ID `#parent`, while rule #2 simply applies to any element with the ID `#child`, wherever it is in the HTML. Notice how this makes rule #2 less specific? Remember that CSS itself doesn't know about the actual HTML it's being applied to, hence my remark about how the number of elements matched *doesn't* influence specificity. – BoltClock Feb 16 '12 at 19:28
  • I see your point, but the id's are supposed to be unique, so `any element with id ` is *supposed* to never match more than one element. That's why I think it's non-intuitive. – Matt Fenwick Feb 16 '12 at 19:34
  • 1
    Indeed. However, the rule about IDs being unique is normative only to HTML, and as it turns out, CSS doesn't enforce the rule. See [this answer](http://stackoverflow.com/a/8753329/106224) for details. – BoltClock Feb 16 '12 at 19:38