Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Specificity | Selectors and Cascade
Introduction to CSS Part I
course content

Course Content

Introduction to CSS Part I

Introduction to CSS Part I

1. Basic Introduction
2. Selectors and Cascade
3. Box Model

bookSpecificity

CSS specificity refers to the importance of a style rule in the cascade. When multiple style rules apply to the same element, the rule with the highest specificity will take precedence and be applied to the element. Specificity is determined by the type, class, and id selectors used in a rule.

A style rule that directly targets an element using an element selector (e.g., div {color: red;}) has lower specificity than a rule that targets an element using a class selector (e.g., .red {color: red;}). A rule that uses an id selector (e.g., #red {color: red;}) has even higher specificity.

html

index

css

index

js

index

copy

In this example, both the .red and #blue rules apply to the div element. However, the #blue rule has higher specificity because it uses an ID selector, so it will take precedence over the .red rule, and the text will be displayed in blue.

There are a few nuances associated with specificity in CSS that a developer should keep in mind:

  • The !important rule can be used to increase specificity. The !important rule can give a style higher specificity and make it take precedence over other styles;
  • Specificity is determined on a per-property basis. Specificity is determined independently for each property in a style rule. For example, consider the following CSS:
html

index

css

index

js

index

copy

In this example, the color property in the .red rule has higher specificity because of the !important rule, so it will take precedence over the color property in the #blue rule. However, the font-size property in the #blue rule has higher specificity than the font-size property in the .red rule as an ID selector, so the font-size property in the #blue rule will take precedence;

  • The location of the style rule determines specificity. If two style rules have the same specificity and apply to the same element, the rule that appears later in the stylesheet will take precedence.
html

index

css

index

js

index

copy

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 6
some-alt