This text will be red.
CSS Specificity
CSS Specificity determines which CSS rule is applied by the browser when multiple rules match the same element. It is a key concept for understanding how styles are applied and how to manage conflicting styles in your CSS.
Understanding Specificity
Specificity is calculated based on the types of selectors used in a CSS rule. It helps in resolving conflicts when multiple CSS rules could apply to the same element.
Specificity Calculation
Specificity is calculated using a four-part value, which can be thought of as a "specificity score." The parts are:
- A: Inline styles (highest specificity)
- B: ID selectors
- C: Class selectors, attributes selectors, and pseudo-classes
- D: Type selectors and pseudo-elements (lowest specificity)
/* Example Specificity Calculation */
html {
/* Specificity: 0,0,0,1 */
}
body .container p {
/* Specificity: 0,0,2,1 */
}
#main-content .text-highlight {
/* Specificity: 0,1,1,1 */
}
Examples
Example 1: Specificity Hierarchy
/* CSS Rules */
div {
color: blue; /* Specificity: 0,0,0,1 */
}
.container div {
color: green; /* Specificity: 0,0,1,1 */
}
#content .container div {
color: red; /* Specificity: 0,1,1,1 */
}
Example 2: Conflicting Styles
/* Conflicting CSS Rules */
h2 {
font-size: 24px; /* Specificity: 0,0,0,1 */
}
p h2 {
font-size: 18px; /* Specificity: 0,0,1,1 */
}
article #content h2 {
font-size: 14px; /* Specificity: 0,1,1,1 */
}