CSS Specificity

tawhiduldev

Tawhidul Islam Khan

Posted on October 30, 2023

CSS Specificity

CSS specificity determines which CSS rule is applied when multiple rules target the same elements. For example, there is a div that has the content "Hello World", we will set a background color to that div. We can set background color in many ways.

  • Inline style
  • Id selector
  • class selector, attribute sector, pseudo selector
  • Element selector

Each way has its specificity hierarchy,

Inline Style: The inline style has the highest specificity and overrides all other styles. For example
<div style="background-color: red">Hello World</div>

Id selector: The id selector has less specificity than the inline style and higher specificity than the class selector and element selector
<div id="box1">Hello World</div>
// in CSS file or style in head
#box1{
background-color: red;
}

Class Selector: class selector, attribute selector has medium specificity: for example:
<div class="box">Hello World</div>
// in CSS file or style in head
.box{
background-color: red;
}

Element Selector: Element selector has low specificity, for example:
<div>Hello World</div>
// in CSS file or style in head
div{
background-color: red;
}

There is an exception: If we use !important, it will override all CSS

💖 💪 🙅 🚩
tawhiduldev
Tawhidul Islam Khan

Posted on October 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

CSS Specificity
css CSS Specificity

October 30, 2023