CSS Combinators
CSS Combinators: Targeting Relationships Between Elements
A CSS combinator connects two selectors to express a DOM relationship—such as elements nested inside a card or paragraphs sitting immediately after a heading. Using combinators cuts down repetitive class names while keeping styles scoped to the exact context you want.
The Four CSS Combinators
- Descendant Combinator (space
):.card pmatches everypanywhere inside.card, even deeply nested ones. - Direct Child Combinator (
>):.menu > limatches only immediatelichildren of.menu, skipping nested sub-menus. - Next-Sibling (Adjacent) Combinator (
+):h2 + pmatches apthat appears immediately after anh2sharing the same parent. - Subsequent-Sibling (General) Combinator (
~):h2 ~ pmatches allpsiblings following anh2under the same parent.
/* Only top-level navigation items */
.primary-nav > ul > li {
display: inline-block;
}
/* Remove top margin on paragraph immediately following a heading */
article h2 + p {
margin-top: 4px;
font-size: 1.05rem;
}
/* Stack spacing between every sibling element except the first */
.form-stack > * + * {
margin-top: 14px;
}
Modern :has() Parent Selector Bonus
Modern browsers also support :has() as a relational pseudo-class—for example, .card:has(img) styles a card only when it contains an image, solving scenarios traditional downward combinators never could.
Common Mistakes to Avoid
- Using descendant spaces when you meant direct child
>:.accordion punintentionally styles nested sub-accordions unless scoped with.accordion > p. - Chaining four or five combinators deep: Long rules like
.main > .content > div > ul > li > aare brittle and slow to refactor. Keep selectors shallow. - Confusing
+with~: Remember+matches strictly the very next sibling element, whereas~matches all matching later siblings.
Frequently Asked Questions
What does the > * + * ("lobotomized owl") pattern do?
.stack > * + * applies margin-top to every direct child that follows another sibling—spacing items evenly without leaving extra margin above the first item.
Can CSS combinators look backward to style an earlier sibling?
Traditional + and ~ only look forward in DOM order, though modern :has() lets you style an earlier element when a later sibling matches (label:has(+ input:required)).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.