CSS class priorities

前端 未结 4 1388
深忆病人
深忆病人 2020-12-08 15:13

I have a question about the priority of CSS classes after encountering a problem today. The situation is as follows:

I have an unordered list which has a class assoc

相关标签:
4条回答
  • 2020-12-08 15:52

    A small addition that was not mentioned by cletus' post.
    According to the W3C link, the highest priority is the style attribute used in the html element/tag.

    E.g. if you have

    <a id= bar style="color: red">foo</a>
    

    and

    <style>
    #bar {
        color: blue;
    }
    </style>
    

    The color will be red because the inline html style has the highest priority, higher than #.

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

    This sounds like a CSS specificity problem. Try changing your .selectedItem ruleset to:

    .dynamicList li.selectedItem {
      background-color: #0000ff;
    }
    
    0 讨论(0)
  • 2020-12-08 16:05

    Change the selectedItem rule to:

    .dynamicList li.selectedItem
    {
        background-color: #0000ff;
    }
    
    0 讨论(0)
  • 2020-12-08 16:06

    The short answer is that your .selectedItem style isn't getting applied because the previous style is more specific and thus has a higher priority. Here is a decent rundown:

    Now, let’s make a general list of the internal priorities for CSS (3 has the highest priority):

    element
    .class
    #id
    

    This is the default priority order. In addition to this, specificity will also count, f.ex ul li will override li. W3C has made a decent table over how you should calculate internal weight:

    LI            {...}  /* a=0 b=0 c=1 -> specificity =   1 */
    UL LI         {...}  /* a=0 b=0 c=2 -> specificity =   2 */
    UL OL LI      {...}  /* a=0 b=0 c=3 -> specificity =   3 */
    LI.red        {...}  /* a=0 b=1 c=1 -> specificity =  11 */
    UL OL LI.red  {...}  /* a=0 b=1 c=3 -> specificity =  13 */
    #list         {...}  /* a=1 b=0 c=0 -> specificity = 100 */
    

    And here is the W3C specification.

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