Understanding CSS selectors

前端 未结 5 914
一个人的身影
一个人的身影 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: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.

    #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;

提交回复
热议问题