When writing CSS, selectors are your primary tool for targeting and styling HTML elements. While basic selectors like element names, classes, and IDs are powerful, sometimes you need more precision—especially when elements are related to each other in the DOM. That’s where CSS combinators come into play.
So, how many types of CSS combinators are there?
✅ There Are Four Types of CSS Combinators
CSS provides four types of combinators, each allowing you to define a different kind of relationship between elements:
- Descendant combinator (
space
) - Child combinator (
>
) - Adjacent sibling combinator (
+
) - General sibling combinator (
~
)
Let’s look at each of these in detail.
1. Descendant Combinator (
)
Syntax:
parent descendant {
/* styles */
}
Description:
Selects all elements that are nested inside a specified element, at any depth.
Example:
div p {
color: gray;
}
Styles every <p>
inside a <div>
, even if it’s deeply nested.
2. Child Combinator (>
)
Syntax:
parent > child {
/* styles */
}
Description:
Selects only the direct child of an element.
Example:
ul > li {
list-style-type: square;
}
Applies styles only to <li>
elements that are immediate children of a <ul>
.
3. Adjacent Sibling Combinator (+
)
Syntax:
element1 + element2 {
/* styles */
}
Description:
Selects an element that is directly after another sibling element.
Example:
h2 + p {
font-size: 1.2em;
}
Targets the first <p>
that comes right after an <h2>
.
4. General Sibling Combinator (~
)
Syntax:
element1 ~ element2 {
/* styles */
}
Description:
Selects all sibling elements that follow a specified element, not just the first one.
Example:
h2 ~ p {
color: darkgray;
}
Styles every <p>
that comes after an <h2>
, as long as they share the same parent.
📋 Quick Comparison Table
Combinator | Symbol | Matches… | Example |
---|---|---|---|
Descendant |
| Any nested element | div p |
Child | > | Direct children only | ul > li |
Adjacent | + | First sibling after element | h2 + p |
General | ~ | All siblings after element | h2 ~ p |
📝 Conclusion
There are four CSS combinators, and each allows you to target elements based on their relationship with other elements:
- Use the descendant combinator when you need to style deeply nested elements.
- Use the child combinator when you want precision with direct children.
- Use adjacent sibling to affect an element right after another.
- Use general sibling to style all siblings that follow a given element.
Mastering CSS combinators is a great way to write more effective, semantic, and maintainable stylesheets.