What is the specificity of the attribute selector?

冷暖自知 提交于 2019-12-17 18:49:22

问题


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

  • Id = 100 points
  • Class = 10 points
  • Html Tag= 1 point

Example:

/* this specificity value is 100 + 10 + 1 = 111 */
#hello .class h2 { }

With this HTML:

<div class="selectform">
<input type="text" value="inter text">
<input type="text" value="inter text" class="inputag">
</div>

Which of these 2 selectors is more specific?

.selectform input[type="text"] { }
.selectform .inputbg { }

Check to demo http://tinkerbin.com/IaZW8jbI


回答1:


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 { }



回答2:


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.



来源:https://stackoverflow.com/questions/11406953/what-is-the-specificity-of-the-attribute-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!