HTML & CSS Interview Question #61

How is CSS specificity calculated?

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

Quick Interview Answer

Specificity is commonly reasoned about in columns: ID selectors; class selectors, attributes, and pseudo-classes; and type selectors and pseudo-elements. The selector with the higher value at the first differing column wins when other cascade factors are equal.

Detailed Explanation

Specificity is commonly reasoned about in columns: ID selectors; class selectors, attributes, and pseudo-classes; and type selectors and pseudo-elements. The selector with the higher value at the first differing column wins when other cascade factors are equal.

Inline styles participate at a higher author-style level than ordinary selector specificity in common cases. Some functional pseudo-classes, such as :is(), :not(), and :has(), derive specificity from their selector arguments, while :where() deliberately contributes zero specificity.

Code Example

/* 0 IDs, 2 class-level, 1 type */
.card .title h2 {
    color: navy;
}

/* 1 ID, 1 class-level */
#content .title {
    color: maroon;
}

/* :where() adds no specificity */
:where(.article) h2 {
    margin-block: 1rem;
}