Mastering CSS Specificity: A Comprehensive Guide
Understanding CSS Specificity
CSS specificity is a fundamental concept that determines which CSS rules are applied to an element when multiple rules could apply. It plays a crucial role in managing conflicts in styles and ensuring that the intended design is achieved.
Key Concepts
- Specificity Hierarchy: Different selectors possess varying levels of specificity. The more specific a selector is, the higher its priority.
- Types of Selectors:
- Inline Styles: Styles applied directly on an HTML element (e.g.,
<p style="color: blue;">
). This has the highest specificity. - IDs: Selectors using an ID (e.g.,
#header
). This represents medium specificity. - Classes, Attributes, Pseudo-classes: Selectors using classes (e.g.,
.class-name
), attributes (e.g.,[type="text"]
), and pseudo-classes (e.g.,:hover
) have lower specificity than IDs. - Elements and Pseudo-elements: Selectors targeting HTML elements (e.g.,
div
,p
,h1
) or pseudo-elements (e.g.,::before
) display the lowest specificity.
- Inline Styles: Styles applied directly on an HTML element (e.g.,
Specificity Calculation
Specificity is calculated using a four-part value (A, B, C, D):
- A: Inline styles (1 or 0)
- B: IDs (number of IDs)
- C: Classes, attributes, pseudo-classes (number of these)
- D: Elements and pseudo-elements (number of these)
Example of Specificity Calculation
Consider the following CSS rules:
#header { color: red; } /* Specificity: 1, 1, 0, 0 */
.content { color: blue; } /* Specificity: 0, 0, 1, 0 */
p { color: green; } /* Specificity: 0, 0, 0, 1 */
If we have the following HTML:
<div id="header">
<p class="content">Hello World</p>
</div>
The #header
rule (specificity 1, 1, 0, 0) will override the .content
rule (specificity 0, 0, 1, 0), and the p
rule (specificity 0, 0, 0, 1) will not apply either.
Conclusion
Understanding CSS specificity is essential for effectively managing styles in web development. By mastering how specificity works, you can avoid conflicts and ensure that the correct styles are consistently applied to your HTML elements.