Isaac.

web

CSS Specificity Explained

Master CSS specificity rules for reliable styling.

By Emem IsaacApril 17, 20222 min read
#css#specificity#selectors#cascade
Share:

A Simple Analogy

CSS specificity is like a voting system. More specific rules override general rules.


Why Specificity?

  • Predictability: Understand which styles apply
  • Debugging: Fix style conflicts
  • Maintainability: Avoid !important hacks
  • Scalability: Write organized stylesheets
  • Cascade: Control inheritance chain

Specificity Calculation

Specificity = (Inline, IDs, Classes+Attributes, Elements)

Examples:
h1                          = (0, 0, 0, 1)
.header                     = (0, 0, 1, 0)
#main                       = (0, 1, 0, 0)
style="color: red"          = (1, 0, 0, 0)

h1.title                    = (0, 0, 1, 1)
div.container p.text        = (0, 0, 2, 2)
#nav ul li a:hover          = (0, 1, 1, 3)

Example Conflicts

/* Specificity (0,0,0,1) - Element */
p { color: black; }

/* Specificity (0,0,1,0) - Class (wins) */
.highlight { color: red; }

/* Specificity (0,1,0,0) - ID (wins) */
#intro { color: blue; }

/* Specificity (1,0,0,0) - Inline (wins) */
<p style="color: green;">Text</p>

Pseudo-Classes & Elements

/* Pseudo-classes add to class specificity */
a:hover                     = (0, 0, 1, 1)
input:focus                 = (0, 0, 1, 1)
ul li:first-child           = (0, 0, 1, 2)

/* Pseudo-elements add to element specificity */
p::first-letter             = (0, 0, 0, 2)
div::before                 = (0, 0, 0, 2)

Avoiding !important

/* Bad - Hard to override later */
.btn { background: blue !important; }

/* Better - Be specific instead */
.btn { background: blue; }
.btn.primary { background: blue; }
.btn.primary:hover { background: darkblue; }

Best Practices

  1. Be specific enough: Don't use overly general selectors
  2. Avoid IDs: Use classes instead for reusability
  3. No !important: Use specificity instead
  4. Naming: Use BEM or similar system
  5. Organize: Group related rules together

Related Concepts

  • CSS cascade
  • Inheritance
  • Media queries
  • Responsive design

Summary

CSS specificity determines which styles win. Master the rules to write maintainable, predictable stylesheets.

Share:

Written by Emem Isaac

Expert Software Engineer with 15+ years of experience building scalable enterprise applications. Specialized in ASP.NET Core, Azure, Docker, and modern web development. Passionate about sharing knowledge and helping developers grow.

Ready to Build Something Amazing?

Let's discuss your project and explore how my expertise can help you achieve your goals. Free consultation available.

💼 Trusted by 50+ companies worldwide | ⚡ Average response time: 24 hours