CSS specificity referes to the rank or priority of a selector.
The universal selector (*
) has the lowest specificity, and id has the highest.
Also, inline styles have a higher specificity than internal or external stylesheets.
This element is lightblue because the inline style has the highest specificity.
<style>
.my-style {
background-color: red;
padding: 20px;
}
</style>
<div class="my-style"
style="background-color:aliceblue;">
The specificity of the inline style is higher
</div>
Four categories define the specificity level of selectors.
They are listed below, sorted from most specific to least specific.
<p style="color:red;">...</p>
..bg-green
, .bordered
.:hover
, :active
, :focus
.[type="text"]
.ul
, div
, and input
.:before
, :after
.CSS styling with multiple selectors can be confusing if you don't know the specificity rules. The image below depicts how each selector is calculated.
The calculated point value for this selector is 0122.
The calculated point value for this selector is 1000.
The calculated point value for this selector is 0001.
For elements that use the same CSS rule or have equal specificity, the one that appears last in
the stylesheet will be applied.
Two equivalent CSS rules are applied to a <p> element.
The style that appears last is used.
This paragraph has an orangered text color
<style>
.mycolor { color: teal; }
.mycolor { color: orangered; }
</style>
<p class="mycolor">
This paragraph has an
orangered text color
</p>
For embedded (external) and internal stylesheets, the style sheet which is closest to the element will be applied.
The example below uses an external CSS stylesheet before the internal CSS.
The style inside the <style> will be used.
/* External CSS file */ #content > div { background-color: lavender; } /* Internal CSS style */ <style> #content > div { background-color: steelblue; } </style>
Finally, the universal selector (*
) and inherited values have the lowest specifity.
Above all selectors, the !important
declaration overrides everything.
Regardless of the selector, the style with !important
declaration will be applied.
The !important
declaration should be used sparingly to avoid style confusion.
In this example, the inline and class selectors are overriden by the element selector with the !important
declaration.
This paragraph has the !important text color.
<style>
p {
color: orangered !important;
}
.teal {
color: teal;
}
</style>
<p class="teal"
style="color: steelblue">
This paragraph has the
!important text color.
</p>