Understanding CSS Cascade and Specificity
Q: Can you explain the CSS Cascade and Specificity rules, including how they affect the ordering and priority of CSS styles on a web page?
- CSS
- Senior level question
Explore all the latest CSS interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create CSS interview for FREE!
The CSS cascade refers to the process by which conflicting
CSS rules are resolved and applied to elements on a web page. When multiple CSS
rules apply to the same element, the cascade determines which rule takes
precedence.
The CSS cascade works by assigning different levels of
importance to CSS rules based on their origin, specificity, and order of
appearance in the stylesheet. These factors are taken into account when
resolving conflicts between rules.
Specificity is a measure of how specific a CSS rule is in
targeting a particular element on a web page. The more specific a rule is, the
higher its priority in the cascade. Specificity is determined by the number of
selectors in a rule, as well as the type of selectors used (IDs, classes, or
elements).
The CSS specificity hierarchy is as follows:
- Inline
styles (e.g. <div style="color: red;">)
- IDs
(e.g. #my-element)
- Classes,
pseudo-classes, and attribute selectors (e.g. .my-class, :hover,
[type="text"])
- Elements
and pseudo-elements (e.g. div, ::before)
In addition to specificity, the order of appearance of CSS
rules in the stylesheet also affects their priority in the cascade. Rules that
appear later in the stylesheet override earlier rules with the same
specificity.
Here's an example to illustrate how the cascade and
specificity rules work:
/* Rule 1 */ div { color: red; } /* Rule 2 */ #my-div { color: blue; } /* Rule 3 */ .my-class { color: green; }
In this example, we have three CSS rules that apply to a div
element on the web page. Rule 1 applies to all div elements, Rule 2
applies to the div element with the ID my-div, and Rule 3 applies
to all elements with the class my-class.
If we have an HTML element like this:
<div id="my-div" class="my-class">Hello world!</div>
The text "Hello world!" will be styled with the
color green, since Rule 3 has higher specificity than Rule 2 and Rule 1. If we
remove the .my-class class from the HTML element, the text will be
styled with the color blue, since Rule 2 has higher specificity than Rule 1.
In general, it's important to write CSS code with
specificity and the cascade in mind to ensure that styles are applied
consistently across a web page.


