Linked Questions

Popular Questions

The order of a descendant combinator CSS definition

Asked by At

This must be a very simple question for HTML ninjas out there, but I feel I'm missing something obvious here. Here is a snippet:

#red span {
  color: red;
}

#green span {
  color: green;
}
<div id="red">
  <p><span>red</span></p>
  <div id="green">
    <p><span>green</span></p>
  </div>
</div>

If I swap the stylesheet order, all of the text becomes red:

#green span {
  color: green;
}

#red span {
  color: red;
}
<div id="red">
  <p><span>red</span></p>
  <div id="green">
    <p><span>green</span></p>
  </div>
</div>

This happens despite the fact that <div id="green"> is a more inner parent of <span>green</span> than <div id="red"> in the DOM tree. I suppose it doesn't take precedence simple because its CSS now appears first in the order of stylesheets. So the order of stylesheets is what matters here.

Is this an expected behavior? Is this implementation/browser specific? Is there some official specs detailing that?

Finally, is there any CSS selector syntax I can use to make it work as in the first snippet, without relying on the order of stylesheets or adding new class names, ids, etc?

Related Questions