Edit Template
  • Home
  • /
  • CSS Specificity
Edit Template
  • Home
  • /
  • CSS Specificity

CSS Specificity

When multiple CSS rules apply to the same HTM element, CSS Specificity helps the browser decide which one to use. It’s like a rulebook for determining which style wins in case of a conflict.

What Is Specificity?

Specificity is the weight or importance assigned to a CSS rule. The more specific the rule, the more likely it is to apply.

Example to Understand Specificity

				
					<!DOCTYPE html>
<html>
<head>
  <title>Specificity - Learn With Arshyan</title>
  <style>
    * {
      color: grey;
    }
    h1 {
      color: teal;
    }
    .heading {
      color: blue;
    }
    #main-title {
      color: crimson;
    }
  </style>
</head>
<body>
  <h1 id="main-title" class="heading" style="color: purple;">Welcome to Learn With Arshyan</h1>
</body>
</html>

				
			
Example to Understand Specificity

Despite all the other rules, the text appears purple because the style attribute has the highest specificity.

Cascade Algorithm

CSS is “Cascading” because it follows this priority chain when applying styles:

  1. Position (the last style wins if specificity is equal)
  2. Specificity
  3. Origin (user agent or author styles)
  4. Importance ( !important overrides everything)

Specificity Hierarchy

Selector Type

Specificity Points

Inline Styles

1000

ID Selectors

100

Class / Attribute / Pseudo-class

10

Element Selectors

1

Universal Selector (*)

0

Specificity Examples

Inline Style

				
					<h2 style="color: orange;">Inline Style Wins</h2>
				
			

Even if the class or ID tries to change this, orange will appear because inline styles = 1000.

ID Selector

				
					<style>
  #highlight {
    color: darkblue;
  }
</style>

<h2 id="highlight">This is styled by ID</h2>

				
			
ID Selector Style Specificity

Specificity = 100

Class Selector

				
					<style>
  .highlight-text {
    color: darkred;
  }
</style>

<p class="highlight-text">Class-based styling</p>

				
			
Class Selector Style Specificity

Specificity = 10

Element Selector

				
					<style>
  p {
    color: seagreen;
  }
</style>

<p>Styled using an element selector</p>


				
			
Element Selector Style Specificity

Specificity = 1

Universal Selector

				
					<style>
  * {
    color: gray;
  }
</style>

<p>This is styled by the universal selector</p>

				
			
Universel Selector Style Specificity

Specificity = 0

Specificity Calculation Example

				
					a.arshyan-class.study-group[href]:hover {
  color: purple;
}

				
			

Breakdown:

  • a = 1 (element)
  • .arshyan-class and .study-group = 10 + 10
  • [href] = 10
  • :hover = 10

Total Specificity = 1 + 10 + 10 + 10 + 10 = 41

!important

If you really want a style to override everything else:

				
					p {
  color: black !important;
}

				
			

Even inline styles won’t beat this. But use !important sparingly, as it makes debugging difficult.

Scroll to Top