CSS specificity determines which styles are applied by the browser when multiple rules could apply to the same element. Specificity is calculated based on the types of selectors used in the rules.
The hierarchy of CSS specificity is as follows (from lowest to highest):
div
, p
).class
, [type="text"]
, :hover
)#id
)style="color: red;"
)Below are examples illustrating different levels of CSS specificity:
/* General styles */
p {
color: black;
}
/* Class selector with specificity */
.class-specific {
color: red;
}
/* ID selector with higher specificity */
#id-specific {
color: blue;
}
/* Inline styles with highest specificity */
.inline-example {
color: green;
}
This text will be black by default.
This text will be red because of the class selector.
This text will be blue because of the ID selector.
This text will be green because of the inline style.