CSS Specificity
When multiple conflicting CSS rules apply to the same element, the browser follows a set of rules to determine which one takes precedence.
Specificity is a concept that helps browsers decide which property value is most relevant to an element. It determines which style declaration gets applied.
Selectors have a hierarchy in terms of specificity. There are four categories that define the specificity level, listed from highest to lowest:
-
Inline styles: Styles directly attached to the element using the
style
attribute. Inline styles have the highest priority. -
IDs: Unique identifiers assigned to elements using the
id
attribute. ID selectors have the second-highest priority. -
Classes, attributes, and pseudo-classes: These include class selectors, attribute selectors, and pseudo-classes like
:focus
,:hover
, etc. -
Elements and pseudo-elements: This category includes element selectors (e.g.,
div
,h1
) and pseudo-elements like:after
and:before
. They have the lowest priority.
Specificity is a measure of the weight applied to a CSS declaration. It is determined by the number of occurrences of each selector type in the matching selector.
Let’s understand it with an example:-
Input:-
Output:-