# CSS Selector Specificity

## Overview

When an element in the browser has a conflict of styles, the browser uses a set of rules to determine which style should be rendered. This set of rules is defined as `CSS Selector Specificity`.

For instance, for an element, if we have the following DOM and CSS classes,

```css
.myClass {
	color: yellow;
}
```

```html
<div style="color: red;" class="myClass">My Text</div>
```

In this case, the color will be `red`, since the inline style has higher weight.

## Calculation

The browser uses an array of four elements, where the previous index has higher priority. Consider these four elements a `a`, `b`, `c` and `d`.

\[a, b, c, d\]

A = Inline styles

B = Number of selector IDs

C = Classes, Pseudo Classes, and Attributes

D = Elements and Pseudo-Elements

We calculate `A`, `B`, `C`, `D` as follows,

```css
body.home #sidebar .menu li a:hover {
  color: gold;
}
```

Let’s break it down:

```javascript
body → element → +1 to d
.home → class → +1 to c
#sidebar → ID → +1 to b
.menu → class → +1 to c
li → element → +1 to d
a → element → +1 to d
:hover → pseudo-class → +1 to c
```

Specificity: 0,1,3,3

## Rules of Specificity

* Higher specificity wins.
    
* If specificity is the same, the last declared rule in the CSS wins.
    
* Inline styles have the highest specificity (except `!important`).
    
* `!important` can override normal specificity but should be used sparingly.
    

## Best Practices

* Write CSS with low specificity, so we can override it later
    
* Avoid nested selectors and keep them shallow
