CSS Specificity / CSS Selector Priority

Laxmi Chapagain
2 min readJun 28, 2021

Cascading Style Sheet (CSS) is responsible for styling our websites. They make websites look the way we want. For example, I have a button that I got from HTML, I want that button to be red. I can simply use the CSS property to have red color on my button. While talking about specificity in CSS, it’s very important in debugging CSS properties because CSS specificity tells which CSS values will be used in our websites.

image from google.com

Below is a detailed explanation of CSS Specificity.

Case 1

index.html

<html><body><h1 id =”heading” class =”title”> Hello World </h1></body></html>

style.css

h1{color:Red;color:Green;}
CSS Specificity using element selector

Case 2

index.html

<html><body><h1 class =”title”> Hello World </h1>}

style.css

h1{
color:Green;
}.title{color: blue;
}
CSS Specificity in between class selector and element selector

Case 3

index.html

<html><body><h1 id =”heading” class =”title”> Hello World </h1></body></html>

style.css

h1{color : Red;color:Green;}.title{color: blue;}#heading{Color : Orange;}
CSS Specificity among element, id, and class selectors

Case 4

Above all, inline CSS is more specific than external CSS.

Let us see an example:

index.html

<html><body><h1 id =”heading” class =”title”   style =”color: pink ;”> Hello World </h1></body></html>

style.css

h1{color : Red;color:Green;}.title{color: blue;}#heading{Color : Orange;}
CSS Specificity among inline CSS and external CSS

Conclusion:

Specificity / Highest priority

  • Inline CSS >Id Selector> Class Selector> HTML element Selector

PS: There is another rule in CSS called! important rule, which overrides all previous styling property on that element. It is recommended not to use this rule in our code.

--

--

Laxmi Chapagain

Learning, sharing and constantly evolving! I make things work because I write codes.