CSS specificity is a set of rules that determines which styles should be applied to an element when multiple conflicting styles are defined. It helps to resolve conflicts and determine the most specific rule to apply.
CSS specificity is calculated based on the selectors used to target elements in the HTML markup. Each selector has a specific weight or value assigned to it, and the rules with higher specificity take precedence over rules with lower specificity.
The following list shows the order of specificity, from highest to lowest:
- Inline styles: Styles defined directly on the HTML element using the
styleattribute. Inline styles have the highest specificity because they are directly applied to the element.
- IDs: Selectors using the ID attribute of an element (
- Classes, attributes, and pseudo-classes: Selectors using classes (
.className), attributes (
[attribute]), or pseudo-classes (
:focus, etc.). They are less specific than IDs but more specific than element type selectors.
- Element types and pseudo-elements: Selectors using element types (
p, etc.) or pseudo-elements (
::after, etc.). They have the lowest specificity.
In the case of conflicting styles, the selector with the highest specificity will take precedence and be applied to the element. If multiple rules have the same specificity, the rule that appears last in the CSS will be applied, following the principle of the cascade.
To increase the specificity of a selector, you can combine multiple selectors together or use more specific selectors such as IDs or classes. For example,
#myId .myClass has a higher specificity than just
Understanding CSS specificity is important for avoiding style conflicts and ensuring that the desired styles are applied correctly to the elements on a web page.