Combinators and Grouping
Combining selectors with descendant, child, and sibling combinators, plus grouping selectors to avoid repetition.
2 menit membaca
Single selectors like .card or p only get you so far. Combinators let you target elements based on their relationship to other elements, and grouping lets you apply the same rule to several selectors at once.
Descendant combinator (space)
.card p {
color: #4b5563;
}<div class="card">
<p>Styled gray.</p>
<div>
<p>Also styled gray — any depth counts.</p>
</div>
</div>A space between two selectors means "any matching descendant, no matter how deeply nested." This is the most common combinator, but it's also the easiest to overuse — a descendant selector like .card p will style every paragraph inside .card, even ones added later by a component you didn't anticipate.
Child combinator (>)
.card > p {
color: #4b5563;
}The > combinator restricts the match to direct children only — the nested <p> inside the inner <div> in the example above would no longer match. Reach for > when you specifically mean "immediate child" and want to avoid accidentally styling deeply nested elements.
Adjacent and general sibling combinators
h2 + p {
margin-top: 0;
}
h2 ~ p {
color: #6b7280;
}+ matches an element immediately following another sibling (here, the first <p> right after an <h2>). ~ matches any sibling that comes after, not just the immediate next one. A common use for + is removing the top margin from the first paragraph after a heading, since the heading's own spacing usually already provides separation.
Grouping selectors
h1, h2, h3 {
font-weight: 700;
line-height: 1.2;
}A comma separates a list of selectors that all get the same declaration block. This is purely a way to avoid repeating yourself — it's identical to writing three separate rules with identical bodies. Group selectors when the shared styling is intentional and likely to change together; if they only coincidentally look similar today, separate rules age better.
Combining combinators
nav ul > li a:hover {
text-decoration: underline;
}Combinators chain together freely: this reads as "a link, hovered, inside a list item that is a direct child of a <ul>, somewhere inside a <nav>." Reading a compound selector right-to-left — "a link... inside a list item... inside a nav" — is usually the easiest way to parse what it targets.