CSS Selectors
Priority and Specificity of Selectors
Understanding the priority and specificity of selectors in CSS is crucial for effectively applying styles and resolving conflicts between multiple rules.
Selector Specificity
Specificity determines which style rule prevails when several could apply to the same element. Each type of selector has an assigned specificity value:
- ID Selector: 100 points
- Class Selector: 10 points
- Type Selector: 1 point
Selector Specificity Example
Let's see how different selectors affect the same element:
And the following HTML:
What color will the text be? The text will be green because the ID selector has the highest specificity (100 points), surpassing the class selector (10 points) and the type selector (1 point).
Specificity in Combined Selectors
Specificity also accumulates when we combine selectors, allowing for more specific and detailed rules.
Combined Specificity Example
And the following HTML:
What color will the text be? Although .text-highlight
and #main-text p
affect the same element, the text will be green because #main-text p
(specificity of 101 points) has higher specificity than .text-highlight
(10 points).
Load Order
When two rules have the same specificity, the one defined later in the CSS prevails.
Load Order Example
Both rules have the same specificity, so the text will be red, as this rule is defined after the first.
Importance of !important
!important
can override specificity and load order but should be used with caution.
!important
Example
Although .text-highlight
has higher specificity, the text will be blue due to the !important
.
Conclusion
Specificity, load order, and judicious use of !important
are fundamental for properly managing styles in CSS. These concepts help you create more robust and maintainable styles.
The next topic will be about common selector errors, where we will learn to avoid frequent problems in using CSS.
You can take the Quiz for this topic:
