CSS Specificity determines which styles are applied when there is a conflict
March 22, 2024 11:40 PM
In CSS, specificity determines which styles are applied when there is a conflict between different CSS rules that apply to the same element. The specificity of a CSS rule is based on the types of selectors it contains. Here's the order of specificity from highest to lowest:
Inline styles: An inline style (added to an element via the
style
attribute directly in the HTML) has the highest specificity. For example:<div style="color: red;">
.IDs: Selectors that contain an ID are next in specificity. For example:
#navbar
.Classes, attributes, and pseudo-classes: Selectors that contain a class, attribute, or pseudo-class are next. For example:
.highlight
,[type='text']
,:hover
.Elements and pseudo-elements: Selectors that contain an element or pseudo-element are the least specific. For example:
div
,::before
.
If two selectors apply to the same element and have the same specificity, the one that comes last in the CSS document will be used.
It's also worth noting that the !important
rule in CSS can override all of the above, but its use is generally discouraged because it can make debugging and maintenance more difficult.
Comments