HTML & CSS Interview Question #54

What is the difference between element, class, and ID selectors?

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

Quick Interview Answer

An element selector targets all matching HTML elements, such as p or button. A class selector targets elements containing a particular class, while an ID selector targets the element with a particular id.

Detailed Explanation

An element selector targets all matching HTML elements, such as p or button. A class selector targets elements containing a particular class, while an ID selector targets the element with a particular id.

Classes are normally the best choice for reusable component styling. IDs have higher specificity and should generally be reserved for unique document relationships, fragment targets, or cases where an ID is semantically useful rather than used simply to increase CSS priority.

Code Example

p {
    color: #374151;
}

.notice {
    font-weight: 600;
}

#page-header {
    min-height: 80px;
}