How to calculate CSS specificity?

Last Update: Apr 26 2024 | BY: Abhinav Verma

G

GILLA DAS

Before starting how to calculate CSS Specificity you need to understand about selector and what is high and low specificity of selector? OK, Then let's start "The universal selector (*) has low specificity", while "ID selectors are highly specificity". 


Calculations Rule of CSS Specificity:

  • Rule 1: The specificity of A is 1 (One element) 
  • Rule 2: The specificity of B is 101 (One ID reference and one element)
  • Rule 3: The specificity of C is 1000 (Inline styling)

For Example

A: h1

B: #content h1

C: <div id="content"><h1 style="color: #ffffff">Heading</h1></div>

CSS Code Work Like

  • Since 1 (or) A < 101 (or) B < 1000 (or) C

The third rule (C) has a greater level of specificity and therefore will be applied.

Upper Example Explanations:

  • On the upper example, the specificity rules determined by the number of each selector type (Rule 1, 2, and 3) in the matching selector (Just see the upper example). 
  • When multiple declarations have equal specificity (h1, #content h1), the last declaration found in the CSS is applied to the element. 
  • Specificity only applies when the same element (h1) is targeted by multiple declarations (ID selector & inline CSS style too, for example, rule 3).
  • As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor (highest specificity of rule 3, means inline CSS code).

0 votes

Your Answer

Email Us: advertise@gdatamart.com

Donate Us: Support to GDATAMART

LifeStyle & Fun

© 2024 GDATAMART.COM (All Rights Reserved)