What is Specificity in CSS: Simple Explanation and Examples
specificity is a rule that decides which style rules apply when multiple rules target the same element. It works like a score system where selectors with higher specificity win and their styles are shown in the browser.How It Works
Think of CSS specificity like a game of priority. When you write CSS, sometimes different rules try to style the same element. Specificity helps the browser decide which rule is more important and should be used.
Each CSS selector has a score based on its type: inline styles have the highest score, then IDs, then classes/attributes/pseudo-classes, and finally element selectors. The browser compares these scores and applies the styles from the selector with the highest score.
Imagine you have several friends giving you advice, but you trust some friends more than others. Specificity is like trusting the advice from your closest friend (highest score) over others.
Example
This example shows how specificity affects which color is applied to the text.
<style>
p { color: blue; }
.class-example { color: green; }
#id-example { color: red; }
</style>
<p class="class-example" id="id-example">This text will be red because the ID selector has higher specificity.</p>When to Use
Understanding specificity helps you write CSS that works as expected without unexpected style conflicts. Use it when you want to control which styles apply, especially in large projects or when using third-party CSS.
For example, if you want to override a style from a library, you can write a selector with higher specificity or use inline styles carefully. It also helps avoid using !important, which can make CSS harder to maintain.
Key Points
- Specificity is a score that decides which CSS rule applies.
- ID selectors have higher specificity than classes or elements.
- Inline styles have the highest specificity.
- Understanding specificity helps avoid style conflicts.
- Use specificity wisely to keep CSS maintainable.