CSS Specificity / CSS Selector Priority
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.
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;}
Case 2
index.html
<html><body><h1 class =”title”> Hello World </h1>}
style.css
h1{
color:Green;}.title{color: blue;
}
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;}
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;}
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.