Selectors: Specificity in CSS
Patricia Cosma
Posted on January 26, 2023
As you write more and more code, you might observe that more than one CSS rule can be applied to an element.
By mistake, you can also double-style an element. In that case, which rule will be applied?
For situations where conflict arises, CSS applies a set of rules and rank them in a specificity hierarchy and apply the 'winner'.
Specificity Hierarchy
There are 4 categories for this hierarchy:
1. Inline styles
This looks and operates much like CSS, but with a few differences. Inline styles affect the tag they are written in directly, without the use of selectors, which are needed in CSS.
/*example*/
<p style="color: green">
2. IDs
This type of selector matches an element from your code depending on the value of the ID selector.
/*HTML*/
<div id="footer">Contact me</div>
/*CSS*/
#footer {
display: flex;
}
3. (Pseudo-)classes & attributes
A pseudo-class is used to define a special state of an element such as active, focus, visited, hover and so on.
/*when the link is clicked*/
a:active {
color: pink;
}
A class would be defined just as the ID selector, with the difference that its value would be based on the class selector.
/*HTML*/
<div class="container">Hello</div>
/*CSS*/
.container {
font-size: 2rem;
}
You can also style your HTML elements that have a specific attributes or attribute values.
/*HTML*/
<a href="https://website1.com">Website 1</a>
<a href="http://website2.com" target="_blank">Website 2</a>
/*CSS*/
a[target] {
background-color: blue;
}
4. (Pseudo-)elements
CSS pseudo-elements are used to style specified parts of an element.
h1::first-letter {
font-weight: 900;
}
On the other hand, elements can be styled as simple as they come in your HTML structure.
h3 {
border-radius: 10px;
}
Calculate Specificity
- Start at 0
- Add 1000 for each inline style (this always has the highest priority - using the !important rule will override the inline style)
- Add 100 for each ID value
- Add 10 for each (pseudo-)class or attribute value
- Add 1 for each (pseudo-)element value.
Example
h1.p -> 1 + 10 -> 11
h1#title -> 1 + 100 -> 101
<h1 style="color: red"> -> 1000 -> 1000
Want to see more examples and have some exercises?
Check this and save it for later. 😍
If you enjoyed this post, you can get more relevant development content by subscribing (no spam!) to my newsletter on my website.
Thank you for reading!
Cover photo by Afif Ramdhasuma on Unsplash
Posted on January 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.