Selector Specificity in CSS (Live Playground)
Selector specificity in CSS determines the priority of styles applied to elements based on the complexity of the selectors used. In this tutorial, you will learn about selector specificity, how it affects the application of styles, and how to calculate specificity values, along with sample code and simple explanations.
Specificity determines which styles are applied to an element when multiple rules target it. The rule with the highest specificity value takes precedence. Specificity is calculated using the following hierarchy:
- Inline styles (highest specificity)
- ID selectors
- Class, attribute, and pseudo-class selectors
- Element and pseudo-element selectors (lowest specificity)
To calculate specificity, count the number of selectors of each type in a rule, and represent them as a series of numbers. The rule with the highest specificity value will be applied.
/* Specificity: 0,0,1,0 */
/* Specificity: 0,1,0,0 */
/* Specificity: 0,0,0,1 */
<p class="special" id="unique">This paragraph will be green.</p>
In this example, the paragraph has three styles competing for the color property. The
#unique rule has the highest specificity (0,1,0,0) and takes precedence, making the paragraph green.
Importance of the !important rule
!important rule can be added to a style declaration to give it higher priority over other rules. This should be used sparingly, as it can make your CSS harder to maintain and override.
color: red !important;
<p class="special">This paragraph will be red.</p>
In this example, the
color: red !important; declaration takes precedence over the
color: blue; declaration due to the
!important rule, making the paragraph red.
In this tutorial, you learned about selector specificity in CSS and how it affects the application of styles to elements. Understanding specificity is essential for maintaining clean, organized CSS and ensuring that your styles are applied correctly. By carefully considering specificity when writing your CSS, you can create more predictable and manageable styles for your web pages.