This tutorial will clarify CSS Specificity, a crucial concept for controlling which styles apply when multiple rules target the same element. Understanding specificity ensures your web designs render exactly as intended.
Specificity: Calculating Specificity, Understanding its Impact
Specificity is a set of rules that determines which CSS declaration is applied to an element when multiple declarations conflict. It's essentially a scoring system that browsers use to decide which style "wins" and takes precedence. Higher specificity means a rule is more "important" and will override less specific rules.
Example 1: Element vs. Class Specificity
/* Specificity: 0,0,0,1 (Element) */
p {
color: blue; /* Less specific */
}
/* Specificity: 0,0,1,0 (Class) */
.my-text {
color: red; /* More specific */
}
Explanation Here, a paragraph with class="my-text"
will be red. The class selector .my-text
has a higher specificity score (0,0,1,0) than the element selector p
(0,0,0,1), making its style take precedence.
Example 2: ID vs. Class Specificity
/* Specificity: 0,0,1,0 (Class) */
.header-title {
font-size: 24px;
}
/* Specificity: 0,1,0,0 (ID) */
#main-header {
font-size: 36px; /* Most specific */
}
Explanation If an element has both a class .header-title
and an ID #main-header
, the ID's style will apply. ID selectors have a specificity of (0,1,0,0), which is significantly higher than a class's (0,0,1,0).
Example 3: Inline Styles Highest Specificity
<p style="color: purple;">This text is purple due to inline style.</p>
/* Specificity: 0,0,1,0 (Class) */
.intro-text {
color: green;
}
/* Specificity: 0,0,0,1 (Element) */
p {
color: orange;
}
Explanation Inline styles, defined directly in the style
attribute of an HTML element, have the highest specificity (represented as (1,0,0,0)). They will always override styles from stylesheets, regardless of other selectors.
Example 4: Specificity Tie-breaking (Order of Appearance)
/* Specificity: 0,0,1,0 */
.button {
background-color: blue;
}
/* Specificity: 0,0,1,0 */
.button {
background-color: green; /* This one wins due to order */
}
Explanation When two or more selectors have the exact same specificity score, the rule that appears later in the stylesheet (or linked CSS files) will be applied. This is known as the "last declared wins" rule.
Example 5: Combined Selectors and Specificity Calculation
/* Specificity: 0,1,1,1 (1 ID, 1 Class, 1 Element) */
#navigation ul.menu li {
list-style: none; /* Strong specificity */
}
/* Specificity: 0,0,1,1 (1 Class, 1 Element) */
.menu li {
list-style: disc;
}
Explanation Specificity is calculated by summing the values of different selector types: Inline styles (1,0,0,0), IDs (0,1,0,0), classes/attributes/pseudo-classes (0,0,1,0), and elements/pseudo-elements (0,0,0,1). The first rule has higher specificity because it includes an ID selector.