HTML & CSS Interview Question #55
What are combinators in CSS?
CSS Fundamentals, Selectors, Cascade, Specificity, Box Model, Units & Typography Mid-Level Intermediate
Quick Interview Answer
Combinators describe relationships between selectors. The descendant combinator targets matching descendants, > targets direct children, + targets the immediately following sibling, and ~ targets later siblings sharing the same parent.
Detailed Explanation
Combinators describe relationships between selectors. The descendant combinator targets matching descendants, > targets direct children, + targets the immediately following sibling, and ~ targets later siblings sharing the same parent.
Combinators are useful for expressing structural relationships, but very deep selectors can tightly couple CSS to the HTML structure and make components harder to refactor.
Code Example
.card p {
margin-bottom: .5rem;
}
.menu > li {
display: inline-block;
}
label + input {
margin-top: .25rem;
}
h2 ~ p {
color: #4b5563;
}