Skip to main content

Command Palette

Search for a command to run...

CSS Specificity

Updated
3 min read
CSS Specificity
M

Frontend developer

In CSS , Specificity is the algorithm used by browsers to determine weightage of CSS declaration which most relevant to apply on element .The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element.

Specificity matters when same element is targeted multiple times and it is used select the most specific declaration from all of the applied declaration.

Specificity order

  • Important tag

!important overrides all other css stylings without calculating css specificity and applied directly to the selected element. if you use the !important tag it will override all previous styling rules for that specific property on that element!

below you can see that the element p get background color of red because of !important tag

<--HTML-->
<p id="text-color">!IMPORTANT</p>

<--CSS-->
#text-color {
background-color: blue;
}

p {
  background-color: red !important;
}
  • Inline styles Inline style is defined in HTML tag itself. Inline styling are the most specific so it will override all the other styles written in the external style sheet.
<p style="color:blue; text-align: center">Inline style</p>
  • External stylesheet

We can write css in another file and than can link to the HTML page using <link rel="stylesheet" href="styles.css">

Specificity calculation take a initial number of (0,0,0,0) (inline, IDs, classes, elements)

1. ID Selector

ID is the most specific selecter to be apply css style among the all the other css declaration and it add value (0,1,0,0)

2. Classes, attributes and pseudo-classes selector

Classes, attributes, and pseudo-classes are most specific to applied after IDs in specificity calculation. and it adds the value to our specificity calculation (0,0,1,0)

3. Elements and pseudo-elements

Elements and pseudo-element comes after class selector in terms of specificity and it adds value to our css specificity calculation(0,0,0,1)

Calculating CSS Specificity calculation

Exm : 1.

header p{ // 2 elements: 0002 */
color:purple;
}
.box{ // 1 class: 0010 */
color:blue
}
#box{  // 1 ID: 0100 - -->`this is more specific to be applied`
color:red;
}

So above you can see Id selecter has higher specificity so style declared with Id applied to element

Exm : 2.

.box:hover{ // 1 class and 1 pseudo class -->1+1=2 class: 0020 
 color:crimson;     --> `it is most specific`
}
.box{ // 1 class: 0010
color:yellow;
}

In above code you can see that class & pseudo class selector has higher specificity than only class selector so the style of class with pseudo class will apply to the element

That's how specificity works with multiple CSS declarations, and how a more specific declaration overrides the other. Thank you for reading it to the end. I hope you understood