CSS Specificity - Hierarchy
CSS Specificity is the set of rules that determine which CSS styles are applied to an element when multiple conflicting styles are present. Understanding CSS Specificity is crucial for web developers to create organized and maintainable stylesheets.
The specificity of a CSS selector is calculated based on the number of ID selectors, class selectors, and element selectors used in the selector.
Here is how specificity is calculated:
| Selector | Specificity |
|---|---|
#id |
100 |
.class |
10 |
element |
1 |
When two or more selectors have the same specificity, the one that appears later in the stylesheet takes precedence.
Let's look at some examples to understand how CSS Specificity works:
In the following example, we have conflicting styles for the same element:
#myDiv {
color: red;
}
.container #myDiv {
color: blue;
}
In this case, the color of the #myDiv element will be blue because the second style has a higher specificity due to the presence of the class selector.
Now, let's consider a scenario where inline styles are used:
<div id="myDiv" style="color: green;">
Inline style
</div>
The color of the #myDiv element will be green because inline styles have the highest specificity.
It is important to use specificity wisely and avoid relying on too many !important declarations as they can make the stylesheet difficult to maintain.
By understanding CSS Specificity, developers can write cleaner, more efficient CSS stylesheets that are easier to manage and troubleshoot.