CHAPTER 41
CSS Specificity
Learn how CSS decides which rule should be applied when multiple selectors target the same element.
01. What is CSS Specificity?
Specificity determines which CSS declaration wins when multiple rules apply to the same element.
ID selectors generally have higher specificity than class selectors.
Class, attribute and pseudo-class selectors generally have higher specificity than element selectors.
When specificity is equal, the later rule can win.
02. Syntax
/* Element */
p { color: blue; }
/* Class */
.text { color: green; }
/* ID */
#title { color: red; }
03. Example
CSS / HTML Example
AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: blue;
}
.text {
color: green;
}
#title {
color: red;
}
</style>
</head>
<body>
<p id="title" class="text">
Which color will appear?
</p>
</body>
</html>
04. Important Points
✓
Inline styles usually have very high priority.
✓
ID selectors have higher specificity than classes.
✓
Classes are generally more specific than element selectors.
✓
Avoid unnecessarily high specificity.
✓
Keep selectors simple and maintainable.
05. Common Mistakes
⚠
Using IDs everywhere for styling.
⚠
Creating extremely long selectors.
⚠
Using !important to solve every specificity problem.
⚠
Not understanding selector order.
06. Real World Use
Specificity becomes important in large websites where many CSS rules and reusable components can affect the same element.
Ready to Practice? 🚀
Open the AIFA CSS Editor and practice this chapter live.
Try It Yourself →
Practice Exercise
Practice Specificity
Create an element with an element selector, class selector and ID selector. Observe which rule is applied.