Search code examples
cssstylesheet

CSS priority of selectors


I've faced a little confusion about the css style replacement priority.
I have this sample code: DEMO HERE

<style>
#list div {
    background-color: #999;
}

#d2 {
    background-color: #fff;
    color:red;
}
</style>
<div id="list">
    <div>item 1</div>
    <div id="d2">item 2</div>
    <div>item 3</div>
    <div>item 4</div>
    <div>item 5</div>
</div>

My question is, Why the second background-color:#fff; in #d2 class doesn't effect on the child div? or better to ask: Why the first rule wins?
I expect that the second rule changes background color of the div

Does anyone can explain this situation?


Solution

  • #list div is higher specificity than #d2 - the former is an ID + element, the latter is only an ID. Therefore any styles in #d2 that are explicitly defined in #list div will be overwritten by the latter selector.

    div#d2 would be of equal specificity as #list div and #list #d2 would be of higher specificity.

    The order of the specificity hierarchy is !important styles, inline styles, IDs, classes, and then elements. Psuedoclasses and psuedoelements have the specificity of a real class or element. Each step in the hierarchy overrides ALL steps below it, so a selector with 10 classes in it will still be overridden by a selector that is a single ID.

    CSS selector specificity is the name for this hierarchical concept. For more information refer to these resources: