Chapter 2. Understanding the Cascade
There’s nothing worse than writing a bunch of CSS only to test it out and find that other styles are being applied instead of the ones you intended. To better understand why this happens, this chapter explains how web browsers determine which styles to apply to which elements using the cascade.
What Is the Cascade?
The cascade is the method by which the browser determines how styles should be applied to elements. Because multiple styles can be applied to the same element, understanding how the cascade works is important in the event that styles are not applied they way you expect them to be. Luckily, it’s not as complicated as it sounds; styles are applied based on the specificity of their selectors as well as the order in which they appear.
Specificity is a measure of how precisely elements are identified based on the CSS selectors used. Specificity is calculated by analyzing the different types of selectors (except the universal selector,
*) that are combined to select an element. A specificity is determined by plugging numbers into
(a, b, c, d):
If the styles are applied via the
bis equal to the number of ID selectors present.
cis equal to the number of class selectors, attribute selectors, and pseudoclasses present.
dis equal to the number of type selectors and pseudoelements present.
When all of these calculations are completed, those numbers are concatenated to ...