What is the specificity of the attribute selector?

前端 未结 3 1333
暗喜
暗喜 2020-12-09 15:47

I\'m wondering what the specificity of the attribute selector is. For example:

  • Id = 100 points
  • Class = 10 points
  • Html Tag= 1 point
相关标签:
3条回答
  • 2020-12-09 16:32

    As someone said earlier in this post "attribute selectors have the same specificity as classes"...i find that not to be true from my experiences... i have used a class name after say an input[type="text"] and it would not override the previous CSS. It's counter-intuitive since input[type="text"] sounds quite broad . You have to use an ID to override which if you are doing inputs for forms you should have an ID on there anyways to properly connect labels.

    0 讨论(0)
  • 2020-12-09 16:33

    Attribute selectors are equally specific to class selectors.

    In your example, the first selector is more specific because there is an additional type selector input that causes it to beat the second selector.

    The specificity of each selector is calculated as follows:

    /* 1 class, 1 attribute, 1 type -> specificity = 0-2-1 */
    .selectform input[type="text"] { }
    
    /* 2 classes                    -> specificity = 0-2-0 */
    .selectform .inputbg { }
    
    0 讨论(0)
  • 2020-12-09 16:47

    In general, all types of selectors are the same; what matters is the number of selectors in the expression. So ID = 1, class = 1, and HTML tag = 1.

    In the event that two selectors have the same specificity, the one that is further down in the CSS file "wins". So make sure you order your CSS references from the general to the specific; libraries like jquery-ui.css go first, while your CSS files go after those.

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