# Specificity

Specificity is calculated by assigning a heavier weight to those selectors that are more specific in nature.

* Tag-name or type selectors are not very specific. A website could have hundreds of `<p>` tags embedded in it making it difficult to target selected groups of them.
* The `class` attribute increases specificity by targeting subsets of elements that have common styling rules beyond the element selector.
* The `id` attribute of an element should be unique within a website making it very specific giving it the highest priority.
* Finally, if an element has inline styling `<p style=“color: brown”>` it automatically overrides all others.

Where specificity is determined to be equal between two competing declaration, the last declaration wins.

To calculate specificity, we count the occurrences of each selector and order them from highest to lowest using the following formula:

`inline-style id class tag-name`

{% tabs %}
{% tab title="CSS" %}
```css
/* Specificity of 0001 */
p {
    color: red;
}

/* Specificity of 0002 */
div>p {
    color: burlywood;
}

/* Specificity of 0010 */
.yellow {
    color: yellow;
}

/* Specificity of 0100 */
#green {
    color: green;
}

/* Specificity of 0100 */
#blue {
    color: blue;
}

/* Specificity of 0100 */
#purple {
    color: purple;
}

/* Specificity of 0012 */
div>p.yellow {
    color: rgb(80, 80, 14);
}
```
{% endtab %}
{% endtabs %}

### Specificity Calculator

{% embed url="https://specificity.keegan.st/" %}

![](https://3069112348-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MR93ctAFfSCsQwng6wL%2F-MZ0p8EIHB17ahBR52fL%2F-MZ0ptJGan0FBWYF6bbA%2FSpecificity.gif?alt=media\&token=dcd02eee-2dbd-4581-b999-93ffb239df84)

### 权重规则总结:

1. !important 优先级最高，但也会被权重高的important所覆盖
2. 行内样式总会覆盖外部样式表的任何样式(除了!important)
3. 单独使用一个选择器的时候，不能跨等级使css规则生效
4. 如果两个权重不同的选择器作用在同一元素上，权重值高的css规则生效
5. 如果两个相同权重的选择器作用在同一元素上：以后面出现的选择器为最后规则.
6. 权重相同时，与元素距离近的选择器生效

!important>行内样式>ID选择器 > 类选择器 | 属性选择器 | 伪类选择器 > 元素选择器
