Specificity
When lines of CSS code expand, different property values can be set for a property of the same element. When a browser encounters this situation, it prioritizes CSS instructions based on the specificity of selectors. Basically, a browser prioritizes instructions for the selectors with higher specificity.
For example, in the case of the code below, the font color of Say hello. becomes red as the descendant selector (section
+ p
) is more specific than the type selector (p
).
<section>
<p>Say hello.</p>
</section>
section p{
color: red;
}
p {
color: blue;
}
Type selector vs. class selector vs. ID selector
Among the three types of selectors, the ID selector is the most specific followed by the class selector. The type selector is the least specific. For example:
- When a type selector and a class selector are pointing at the same element, the class selector is prioritized.
- When a type selector, a class selector, and an ID selector are pointing at the same element, the ID selector is prioritized.
Descendant selectors
A combination of selectors (descendant selectors) can increase specificity. As we explained at the top of this lesson, two type selectors (section
+ p
) have higher specificity than a single type selector (p
).
Calculation of selector specificity
There is a rule to calculate specificity. Basically, each selector group has a specificity value.
- Type selector: 1
- Class selector: 10
- ID selector: 100
When you use a descendant selector (a combination of selectors), sum up the points.
You can check the W3C website for details – W3C: Calculating a selector's specificity.
Inline styling
Inline styling (directly written in the start tag of each element using the style
attribute) gives higher specificity. The CSS code written in inline style has higher specificity than the ID selector.
!important
!important
is a special keyword used to increase the priority of a specific CSS declaration. You can use the keyword right after the property value where you want to prioritize. The CSS declaration with this keyword overrides even inline styling.
This is an example of a CSS declaration with the !important
keyword.
p {
color: black !important;
}