1
0
0
CSS Specificity,How CSS Rules will Win out over another Rule image
HTMLCSS
createor-profile-picture
Spurgeon Gnan Prakasham Tara
creator

Nov 27, 2024

CSS Specificity - How CSS Rules Cascade and will Win out over another Rule. Greater the Specificity, Greater the chance that the CSS Rule gets applied

Hello everyone, welcome to WebDevPlusPlus – your one-stop destination for all things web development! So far, we’ve explored CSS Selectors, CSS Combinators, and CSS Inheritance.

In this post, we’re diving into CSS Specificity – a tricky but essential topic in CSS. It’s something that many courses and tutorials don’t cover, but it’s crucial if you want to become a great frontend developer. Consider yourself lucky to have found WebDevParadise!

Let’s get started and master CSS Specificity together!

Topics covered in this article

What is Specificity in CSS?

Specificity determines how CSS rules are applied and which rule takes priority when multiple rules target the same HTML element. Simply put, every CSS rule has a weight, called specificity, that tells the browser which rule to apply. The browser uses this information to decide which styles should be applied. It might sound tricky, but it will make sense as you read through this blog post. Let’s dive in and learn more!

Now, Before moving further, let's take a look at how our code files for this article looks like.

Starter code for this blog post

In your machine, create a folder named specificity. Within that folder create the following two files.

  1. Create an empty CSS file named styles.css
  2. Create an HTML file named index.html and paste the below code in this file.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <h1 class="heading" id="header">Main Heading</h1> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13

The above code is straightforward. It contains a basic HTML boilerplate with an h1 tag inside the body. The h1 tag has a class name (heading) and an id (header). The CSS file is already linked to the HTML file.

When you save the HTML file and open it in your browser, it will look like this:

Starter Files Preview

Now, let’s dive into the core topic—CSS Specificity.

CSS Default Cascading

Before moving into Specificity, Lets see the default CSS cascading behavior. In your CSS file add the below style.

css
h1 { color: blueviolet; }
1
2
3

Now save the files and reload the browser.

CSS Default behavior one

As you can see, the styles were applied successfully.

Now add one more style as below to the same h1 element with color: green.

css
h1 { color: blueviolet; } h1 { color: green; }
1
2
3
4
5
6
7

Now save the file and reload the browser

CSS Default Behaviour two

As you can see, the first style with color: blueviolet is ignored, and color: green is applied to the h1 tag. This happens because both CSS rules have the same specificity (element-level).

This is the default behavior in CSS. The browser scans the CSS file from top to bottom and applies the style that appears last.

In this case, the browser replaced blueviolet with green because the most recent style for color was green. However, the real challenge arises when we target the same element with rules of different specificity weights. Let’s explore that scenario now.

The real fight between multiple CSS rules

When we apply multiple styles to a single HTML element using different CSS rules with varying specificity weights, a "collision" or "conflict" between these rules occurs.

To see this in action, add the following style to the top of your CSS file, above all other rules:

css
.heading { color: orange; }
1
2
3

Now your CSS file will look like this:

css
.heading { color: orange; } h1 { color: blueviolet; } h1 { color: green; }
1
2
3
4
5
6
7
8
9
10
11

If you save the files and reload the browser. You will see some thing like this:

The Real Fight between CSS rules One

Woah! Wait, what? Why is the color from the top rule (color: orange) being applied instead of the green color at the bottom of the file?

Welcome to the concept of Specificity in CSS! This behavior happens due to the specificity of the CSS rules. In this case, we are using a class selector, and the specificity of a class selector is higher than that of an element selector.

As a result, the CSS rule with the class selector (.heading {}) overrides the rule with the element selector (h1 {}). That’s why the color orange is applied instead of green.

CSS Specificity Priorities

The specificity priorities of different selectors in CSS are illustrated below:

CSS Specificity Priority Chart

As shown in the chart, the priority order is:
!important > ID Selector > Class Selector > Element Selector.

For now, ignore !important. We'll discuss it at the end of this article.

Now, let's create a Specificity Chart for the styles we've written so far:

Specificity Chart 1

As you can see:

  1. For .heading {}, we have: 0 !important, 0 IDs, 1 class, 0 elements.
  2. For h1 {}, we have: 0 !important, 0 IDs, 0 classes, 1 element.

To determine which style wins, we analyze the specificity from left to right in the table:

  • !important: Both selectors have 0 !important declarations (we're ignoring !important for now).
  • IDs: Both selectors have 0 IDs, so we move to the next column.
  • Classes: .heading {} has 1 class, while h1 {} has 0 classes. Therefore, .heading {} wins since class selectors have higher specificity than element selectors.

This is why the orange color defined in .heading {} is applied instead of the green color in h1 {}.

Additional Notes:

  • If the number of classes is also equal, the next column (elements) is considered.
  • If both classes and elements are equal, the browser applies the style that appears last in the CSS file, following the default cascading order.

Now that you understand specificity priorities, let's add a new CSS rule with an ID selector at the top of the styles we've written so far and see how it behaves.

Add the following style to your CSS file:

css
#header { color: red; }
1
2
3

Now your CSS file will look like this:

css
#header { color: red; } .heading { color: orange; } h1 { color: blueviolet; } h1 { color: green; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Save the file and reload the browser.

Now, If we plot the Specificity chart, It will look like this:

Specificity Chart 2

As you can see:

  1. For #header {}, we have: 0 !important, 1 ID, 0 classes, 0 elements.
  2. For .heading {}, we have: 0 !important, 0 IDs, 1 class, 0 elements.
  3. For h1 {}, we have: 0 !important, 0 IDs, 0 classes, 1 element.

Checking Specificity Step by Step

  • !important: All selectors have 0 !important declarations, so we move to the next column.
  • IDs: #header {} has 1 ID, while the other selectors have 0 IDs. Since IDs have the highest specificity after !important, the #header {} rule wins.

This is why the color red from #header {} is applied, as shown in the example below:

Id Selector Specificity usage


More specificity Usage

Now, let's add another CSS rule at the very top of our CSS file above all the previous rules. Add the following style:

css
.heading#header { color: brown; }
1
2
3

Now, Our CSS file will look like this:

css
.heading#header { color: brown; } #header { color: red; } .heading { color: orange; } h1 { color: blueviolet; } h1 { color: green; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Now let’s update the specificity chart:

Specificity Chart 3

How the Browser Resolves Specificity

  1. The browser first looks for the style with the most IDs.

    • Here, we have two styles with 1 ID: #header {} and .heading#header {}.
  2. Since both styles have the same number of IDs, the browser moves to the next column in the specificity chart: classes.

Specificity Chart 4

  1. .heading#header {} has 1 class, while #header {} has 0 classes.
    • As a result, .heading#header {} wins the specificity fight, and the color brown is applied, as shown below:

More Left to Right Specificity

Key Takeaways for Calculating Specificity

When calculating specificity, always move from left to right in the specificity chart:

  1. Start with IDs. The style with more IDs wins.
  2. If there is a tie in IDs, compare classes.
  3. If there is still a tie, compare the number of elements.
  4. If everything is tied, the browser will use its default behavior and apply the style that appears last in the CSS file.

Important Note:

Even if a CSS rule contains a very large number of classes, a single ID will always have higher specificity. That’s the power of IDs in CSS specificity.


Let’s Practice Further

In the HTML file, add two more classes (heading-main and heading-top) to the <h1> element. Your updated HTML will look like this:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <h1 class="heading heading-main heading-top" id="header">Main Heading</h1> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13

Now add the following style at the top of our CSS file as shown below:

css
.heading-main.heading-top#header { color: blue; }
1
2
3

Now our CSS file will look like this:

css
.heading-main.heading-top#header { color: blue; } .heading#header { color: brown; } #header { color: red; } .heading { color: orange; } h1 { color: blueviolet; } h1 { color: green; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Drawing the Specificity Chart

First, the browser checks the ID count for all the CSS rules. In this case, three CSS rules have 1 ID:

More Specificity Example One

Since all three rules have the same number of IDs, the browser then checks for the highest number of classes among these rules.

More Specificity Example Two

As shown above, .heading-main.heading-top#header {} has 2 classes, which is the highest. Therefore, the browser applies the styles from .heading-main.heading-top#header {}. The resulting color is blue, as demonstrated below:

More Specificity Example Preview

Inline Styles VS Specificity

Inline styles always take precedence over internal and external styles unless a style is marked with the !important value. To demonstrate this, let’s add an inline style to the <h1> tag in our index.html file as shown below:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <h1 class="heading heading-main heading-top" id="header" style="color: yellow" > Main Heading </h1> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Now save the html file and reload the browser.

Inline Styles VS Specificity

!important Usage

The !important declaration has the highest priority in CSS, even overriding inline styles. When a CSS rule includes !important, it will take precedence regardless of the number of IDs, classes, or elements in competing rules. Let’s explore this behavior.

Update the style h1 { color: blueviolet; } in your CSS file to include !important, as shown below:

css
h1 { color: blueviolet !important; }
1
2
3

Now, Your CSS file will look like this:

css
.heading-main.heading-top#header { color: blue; } .heading#header { color: brown; } #header { color: red; } .heading { color: orange; } h1 { color: blueviolet !important; } h1 { color: green; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Now lets plot the Specificity chart.

!important Specificity Chart

As you can see for h1 selector we have !important value with one, which is greater than all other selectors in our example. And browser will ignores all other selectors and apply this selector with !important as shown below:

CSS Default behavior one

Conclusion

That's it for this post, everyone! I hope you found it helpful and enjoyed learning about CSS specificity.

Key Takeaways:

  • When selecting HTML elements, always refer to a specificity chart like the one we discussed, or use tools like the Specificity Calculator to calculate specificity and understand which styles get applied to your elements.
  • Avoid using inline styles or !important, unless absolutely necessary, as they can make your CSS harder to maintain and debug.

Thank you for reading! Stay tuned to WebDev Paradise for more informative posts like this. Until next time, happy coding! 🚀

Please signin to view resources

Comments

No Comments Found

Follow Us:

Related Posts

View All
Welcome to 'CSS for Everyone' - where you learn all about CSS from Beginning to Advanced

Welcome to 'CSS for Everyone' - where you learn all about CSS from Beginning to Advanced

Welcome, Learn essential CSS concepts and stay up-to-date with the latest trends and techniques in web design. Join us to enhance your CSS skills today.

Read more
Introducing CSS -  What is CSS?

Introducing CSS - What is CSS?

Introduction to CSS. What is CSS and How to use it to design your web layouts and components to become a better frontend developer.

Read more
How to ADD (or) CONNECT our CSS with HTML

How to ADD (or) CONNECT our CSS with HTML

Discover how to connect CSS with HTML using inline, internal, and external stylesheets. This beginner-friendly guide covers methods and examples to style in css

Read more
Mastering CSS Selectors: Your Complete Guide to Targeting HTML Elements for frontend web developers

Mastering CSS Selectors: Your Complete Guide to Targeting HTML Elements for frontend web developers

Mastering CSS Selectors: Guide for Targeting HTML Elements using HTML Element Selector, ID Selector, Class Selector , Attribute Selector, Universal Selector

Read more
Mastering CSS Combinators: An Efficient way of Selecting HTML Elements for Frontend Web Developers

Mastering CSS Combinators: An Efficient way of Selecting HTML Elements for Frontend Web Developers

CSS Combinators: Selectors, Descendant Combinations, Child Combinations, Sibling Combinations, and More

Read more