Understanding CSS selectors

前端 未结 5 912
一个人的身影
一个人的身影 2020-12-16 07:58

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}

         


        
相关标签:
5条回答
  • 2020-12-16 08:05

    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.

    0 讨论(0)
  • 2020-12-16 08:06

    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;

    0 讨论(0)
  • 2020-12-16 08:06

    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?

    0 讨论(0)
  • 2020-12-16 08:12

    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.

    0 讨论(0)
  • 2020-12-16 08:29

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

    0 讨论(0)
提交回复
热议问题