specificity in CSS
testYourself CSS897
Specificity is the way browsers decide which CSS property values are most important for an element, and therefore will be applied.
When two or more CSS rules have the same specificity, the order of the rules determines the end result.
If the specificity is different, the rule with the higher specificity decides what we see in the browser.
The specificity order
The following list of selector types increases by specificity:
- type selector, pseudo-element selector
- class selector, attribute selector, pseudo-class selector
- id selector
- inline styles
!important
Class selector
The class selector has higher specificity than type selector:
css:
.title { color: blue; }
div { color: brown; }
html:
<div class="title">the website title</div>
result:
Id selector
The id selector has the higher specificity than class selector:
css:
#title { color: purple; }
.title { color: yellow; }
html:
<div id="title" class="title">the website title</div>
result:
Inline styles
Inline styles added to an element always overwrite any styles in external and internal stylesheets and can therefore be considered with the highest specificity.
css:
p {
color: green;
}
html:
<p style="color: red">welcome</p>
result:
welcome
Universal selector, combinators
The universal selector (*
), combinators (+
, >
, ~
, '
') and the negation pseudo-class (:not()
) have no effect on specificity.
The negation pseudo-class (:not()
) has no effect on specificity but what is inside brackets does (e.g. div
).
css:
div > p { color: red; }
div p { color: green; }
html:
<div>
<p>example paragraph</p>
</div>
result:
example paragraph
!important
When a !important
rule is used in a style declaration, that declaration overrides any other declarations. Although technically !important
has nothing to do with specificity, it interacts directly with it.
css:
#title { color: blue; }
p { color: orange !important; }
html:
<p id="title">the website title</p>
result:
the website title
a !important
rule overrides even inline styles.
css:
p {
color: green !important;
}
html:
<p style="color: red">welcome</p>
result:
welcome
When two conflicting declarations with the !important
rule are applied to the same element, the declaration with a greater specificity will be applied.
css:
#el {
color: red !important;
}
.my-class {
color: yellow !important;
}
html:
<p class="my-class" id="el">example paragraph</p>
result:
example paragraph
Embedded styles
No matter if there are internal or external styles, the rule with the highest specificity wins. If rules have the same specificity, the order of the rules matters.
style1.css:
p { color: blue; }
style2.css:
p { color: green; }
html:
<link href="style1.css" rel="stylesheet" />
<link href="style2.css" rel="stylesheet" />
<p>example paragraph</p>
result:
example paragraph