views:

647

answers:

5

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?!

+4  A: 

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.

sykora
Your answer was just as good as the one I ticked but I felt the star wars explanation might help people understand it better in the future. I +1 your answer to try and compensate :)
Daniel
A: 

That seems to be the way it works (sometimes frustratingly), an id selector is more specific than a class.

Andrew
A: 

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?

jacobangel
+1  A: 

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;

olemarius
+4  A: 

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.

Andy Ford