Specificity determines which styles take precedence in case of conflicts. Higher specificity overrides lower specificity.
-
Number of IDs (Highest specificity): Each ID selector in the rule increases specificity by 100.
- Example:
#element
has higher specificity than.class
.
- Example:
-
Number of classes and attributes: Each class or attribute in the selector increases specificity by 10.
- Example:
.class
has higher specificity thanelement
.
- Example:
-
Number of elements and pseudo-classes: Each element or pseudo-class (e.g.,
:hover
) in the selector increases specificity by 1.- Example:
div
has higher specificity than:hover
.
- Example:
-
!important (Highest specificity): The CSS declaration value with
!important
has the highest specificity and always overrides other styles.
If there is a conflict between styles, the browser will apply the rules with higher specificity. If the specificity is the same, the browser will apply the rules that appear later in the code (cascade rule).
Examples of Specificity:
#element
is more specific than.class
..class1.class2
is more specific than.class1
.div p
is more specific thanp
..class !important
has the highest specificity and always takes precedence.
Understanding specificity correctly is crucial to avoid unexpected conflicts in CSS code and effectively control which
styles will be applied to HTML elements. In practice, it is recommended to avoid overusing !important
and creating
overly complex selectors to maintain readability and control over the CSS code.