Reputation: 5136
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?
Upvotes: 1
Views: 122
Reputation: 1545
The priority is: inline css > id > class > element. So if you had this
div {
background-color: #999;
}
#d2 {
background-color: #fff;
color:red;
}
then #d2 wins the battle but here:
#list div {
background-color: #999;
}
#d2 {
background-color: #fff;
color:red;
}
'#list div' win because '#list div' selector is stronger as a combination than just '#d2' , by an element.
Upvotes: 1
Reputation: 3175
because of https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity.
to solve this you will need a more specific selector:
#list div {
background-color: #999;
}
#d2 /*not specific enough*/,
div#d2 /*more specific - specific enough*/,
#list #d2/* even more specific*/ {
background-color: #ffffff;
color:red;
}
Upvotes: 1
Reputation: 3763
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have an id selector, but the first one also has a tag selector
Upvotes: 1
Reputation: 10190
#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:
Upvotes: 3