HTML & CSS Interview Question #60

What is CSS specificity?

CSS Fundamentals, Selectors, Cascade, Specificity, Box Model, Units & Typography Mid-Level Intermediate

Quick Interview Answer

Specificity is one part of the cascade used to compare competing selectors within the relevant cascade context. IDs contribute more specificity than classes, attributes, and pseudo-classes, while type selectors and pseudo-elements contribute a lower level.

Detailed Explanation

Specificity is one part of the cascade used to compare competing selectors within the relevant cascade context. IDs contribute more specificity than classes, attributes, and pseudo-classes, while type selectors and pseudo-elements contribute a lower level.

Specificity should be kept manageable. Excessively specific selectors make later overrides difficult and often lead to unnecessary !important declarations.

Code Example

/* Lower specificity */
button {
    color: black;
}

/* Higher specificity */
.toolbar .button {
    color: navy;
}

/* ID selectors are even more specific */
#admin .button {
    color: darkred;
}