Why is it that the below makes the text red?
#stories li a {color:red}
.default li.expand a {color:green}
li.expand a {color:blue}
<ul id="stories" class="default">
<li>this is the end</li>
<li class="expand">this is the end</li>
Only if I put #stories on the others will the text change. Does a # have more dominance even though it's further up the css?!
It's a matter of "CSS Specificity". Andy Clarke's article CSS: Spcificity Wars does a pretty good job explaining it with a little humor. Although Eric Meyer adds more clarity in his comment.
According to http://htmldog.com/guides/cssadvanced/specificity/, '#' (An id selector) has the highest specificity, so yes, anything with a '#' will precede anything which doesn't, if they refer to the same thing.
Check that link for more info.
Basics:
As long as you use the same selectors, this is true:
Inline styles has priority 1
Styles defined in head has priority 2
Styles in linked stylesheet has priority 3
But there's also further priority rules
If you only use linked stylesheet or define styles in head, this is true:
Priority 1: ID's (because there can be only one)
Priority 2: .classes (because there must be a .class added)
Priority 3: tags (lowest priority because no .class or ID's are attached)
The closer the ID is to body, the higher the priority.
<div id="first-id">
<div id="second-id">
<div class="someclass">
</div>
</div>
</div>
#first-id .someclass {}
beats
.someclass {}
as well as
#second-id .someclass {}
BUT
You can make .someclass beat the ID's by using
.someclass { color:#f00 !important;}
But I'm not sure about the browser support on !important;
That seems to be the way it works (sometimes frustratingly), an id selector is more specific than a class.
Selectors work based on how specific a rule is. An id uniquely identifies a specific element, so it is as specific as you can get.
Take this example:
<ul id="stories" class="default">
<li>this is the end</li>
<li class="expand">this is the end</li>
</ul>
<ul class="default">
<li>this is the end</li>
<li class="expand">this is the end</li>
</ul>
<ul>
<li>this is the end</li>
<li class="expand">this is the end</li>
</ul>
How would you target just the #stories list if the selectors didn't work that way?