Understanding CSS Specificity: How Browsers Compute CSS Rules

Taming stylesheet conflicts. We analyze specificity weighting calculations and best practices for clean classes.

VP
SHIVAM ITCS
·14 May 2013·10 min read·1 views

The Cascading Conflict

As CSS stylesheets grow, styles conflict. A developer writes a class to change a button background, but the color remains unchanged because a different selector overrides it.

To resolve these conflicts, developers often use !important, which quickly ruins the cascade structure.

Understanding how browsers calculate CSS Specificity is essential to avoid stylesheet bugs.

CSS Rule: Never use !important to resolve specificity conflicts. It creates styling traps that are hard to debug in large projects.

The Specificity Weighting Algorithm

Browsers evaluate selector specificity using a four-digit numeric weighting system (A, B, C, D):

  1. 1.A (Inline Styles): Styles declared directly on HTML elements. Weight: 1000.
  2. 2.B (ID Selectors): E.g. #dashboard. Weight: 100.
  3. 3.C (Classes and Attributes): E.g. .btn, [type="text"]. Weight: 10.
  4. 4.D (Elements and Pseudo-elements): E.g. div, ::before. Weight: 1.
Selector ExampleA, B, C, D ScoreTotal Specificity
#dashboard .btn0, 1, 1, 0110
.main-content p span0, 0, 1, 212
div0, 0, 0, 11

Specificity Code Comparison

csscode
/* High specificity selector */
#navbar .menu-item a {
  color: #00e5ff; /* Weight: 100 + 10 + 1 = 111 */
}

/* Low specificity class selector */
.link-primary {
  color: #7c4dff; /* Weight: 10 = Will be ignored! */
}

By writing flat, class-based CSS selectors and avoiding ID tags for styling, you keep specificity low and maintainable.

VP
Vijay Paliwal
Founder, SHIVAM ITCS · 18+ years enterprise & AI engineering
MCA · Ex-HiveGPT USA · Ex-Social27 Seattle
Understanding CSS Specificity: How Browsers Compute CSS Rules | SHIVAM ITCS Blog | SHIVAM ITCS