CSS Specificity is a crucial concept in understanding how browsers decide which styles to apply when multiple CSS rules target the same HTML element. It's essentially an algorithm that calculates the "weight" or relevance of a selector. The selector with the highest specificity score wins, and its styles are applied.
Specificity is calculated based on the types of selectors used in a CSS rule. It's often represented as a four-part value, typically in the format of ID - CLASS - TYPE.
style attribute. Specificity: (1,0,0,0).#my-id adds (1,0,0)..my-class, [type="text"], :hover) each add (0,1,0).p, ::before) each add (0,0,1).*, +, >, ~ add nothing.Note: pseudo-classes like :is(), :has(), and :not() themselves don't add specificity, but their contents do.
If two selectors have the exact same specificity, the later rule in the stylesheet wins. The !important rule overrides all specificity but should be used sparingly.
Let's consider an <h1> element with these rules:
<h1 id="main-title" class="section-heading">Hello World</h1>h1 {
color: blue; (0,0,1)
}
.section-heading {
color: green; (0,1,0)
}
#main-title {
color: red; (1,0,0)
}
#main-title.section-heading {
color: purple; (1,1,0)
}The <h1> will be purple because the last rule has the highest specificity (1,1,0).
Write a selector with a higher specificity than the one you want to override. For example:
p {
color: blue;
}
.content p {
color: green;
}The !important declaration overrides all specificity rules:
p {
color: blue !important;
}When two rules have the same specificity, the later one wins:
.box {
color: red;
}
.box {
color: blue;
}Inline styles have the highest specificity and can only be overridden by !important.
<p style="color: blue;">This text is blue.</p>p {
color: red !important;
}