CSS specificity determines which CSS styles are applied to an element. It is a mechanism that defines the priority of different styles, and which styles should be applied when multiple styles are conflicting.
Specificity is calculated based on the following four components:
- Inline styles: Styles directly applied to an element using the
style
attribute have the highest specificity.
- IDs: Selectors that use IDs have higher specificity than classes, pseudo-classes, and elements. An ID selector is represented by a "#" symbol followed by the ID name. Example:
#myId
.
- Classes, pseudo-classes, and attributes: Selectors that use classes, pseudo-classes, and attributes have a higher specificity than elements. Class selectors are represented by a "." symbol followed by the class name. Example:
.myClass
.
- Elements and pseudo-elements: Selectors that use elements and pseudo-elements have the lowest specificity. Example:
p
.
If multiple styles are conflicting, the style with the highest specificity is applied. If two styles have the same specificity, the last style declared wins.
Example:
#header p { color: red; } .warning { color: blue; } <p class="warning">Hello World!</p>
In this example, both selectors
#header p
and .warning
apply to the <p>
element, but the selector with the higher specificity (#header p
) wins and the text will be red.
Loading Comments...