In CSS, specificity determines which styles are applied when multiple CSS rules target the same HTML element. It’s like a ranking system that helps the browser decide which rule to use when there’s a conflict.
The more specific a rule is, the higher priority it has over other, less specific rules. CSS specificity is calculated based on the types of selectors used in a rule.
Selectors in CSS can have different "weights" based on their type. The more specific a selector, the higher its weight, and the more likely it is to be applied over other styles.
Here’s how different selectors contribute to specificity:
- Inline styles (e.g.,
style="color: blue"
) are the most specific and will override all other styles. - ID selectors (e.g.,
#header
) are very specific and have more weight than other types of selectors. - Class selectors, attribute selectors, and pseudo-classes (e.g.,
.button
,[type="text"]
,:hover
) have medium specificity. - Element selectors (e.g.,
div
,p
,h1
) and pseudo-elements (e.g.,::before
,::after
) have low specificity.
Consider the following rules:
/* Rule 1 */
h1 {
color: red;
}
/* Rule 2 */
.header {
color: blue;
}
/* Rule 3 */
#main-header {
color: green;
}
If you have an <h1>
element with the class .header
and an ID #main-header
, CSS will calculate specificity to determine which color to apply:
h1 { color: red; }
has the lowest specificity (element selector)..header { color: blue; }
is more specific (class selector).#main-header { color: green; }
is the most specific (ID selector).
In this case, the <h1>
element will be green because the #main-header
rule is the most specific.
- Inline styles: Highest specificity
- ID selectors: Higher specificity than classes and elements
- Class selectors, attribute selectors, pseudo-classes: Medium specificity
- Element selectors, pseudo-elements: Lowest specificity
- If two rules have the same specificity, the one that comes later in the CSS file will be applied.
- !important can be used to force a style, but it should be avoided in most cases because it overrides normal specificity rules.
Understanding specificity is crucial for controlling the appearance of elements and debugging CSS when styles don’t seem to apply as expected.