Introduction
CSS combinators define relationships between elements, allowing precise styling. They include descendant (
), child (>
), adjacent sibling (+
), and general sibling (~
).
1. Descendant Combinator (
)
Targets elements nested within a specific parent.
Example:
div p {
color: blue;
}
CSSThis styles <p>
inside <div>
but not direct children only.
2. Child Combinator (>
)
Selects direct children only.
Example:
div > p {
font-weight: bold;
}
CSSThis affects only <p>
elements directly inside <div>
.
3. Adjacent Sibling Combinator (+
)
Targets an element immediately following another.
Example:
h1 + p {
font-style: italic;
}
CSSStyles the first <p>
after <h1>
.
4. General Sibling Combinator (~
)
Applies styles to all matching siblings after a given element.
Example:
h1 ~ p {
color: red;
}
CSSStyles all <p>
elements after <h1>
.
5. Combining Combinators
You can mix combinators for complex selections.
Example:
div > p + span {
text-decoration: underline;
}
CSSThis targets <span>
that follows <p>
inside <div>
.
Conclusion
Combinators provide advanced element targeting, enabling cleaner and more efficient CSS code.