CSS Specificity

When more than one conflicting rules of CSS indicates the same element, then the browser will follow some rules for determining the particular one.

Specificity is the way which helps the browsers to decide which property value is most relevant for the element. It determines which style declaration is applied to an element.

Each selector has a place in the hierarchy. There are mainly four categories that define the selector’s specificity level in the highest to lowest order:-

  • Inline styles: It is directly attached to the element which is to be styled. For example: <p style=”color: red;”>. It has the highest priority.
  • IDs: It is a unique identifier for the elements of a page that has the second-highest priority. For example: #para.
  • Classes, attributes, and pseudo-classes: It includes classes, attributes, and pseudo-classes (like :focus, :hover, etc.).
  • Elements and pseudo-elements: It includes the name of elements (div, h1) and pseudo-elements (like :after and :before). They have the lowest priority.

Specificity is the weight, which is applied to the CSS declaration. It is determined by the number of every selector type in the matching selector. Let’s understand it with an example:-


    <div id="div1"> Welcome to the world of styling</div> </body>
text-align: center;  
font-size: 30px;  
color: #fff;  
background-color: brown;  
#div1 {  
background-color: red;  
background-color: #333;  
div[id=div1] {  
background-color: blue;