Combinators in CSS
? CSS Combinators
Combinators in CSS are special characters that describe the relationship between selectors — how elements are related in the HTML structure. They help you target elements more precisely.
Types of CSS Combinators
| Combinator | Symbol | Description | Example Selector |
|---|---|---|---|
| Descendant | (space) | Selects elements inside another element, at any depth. | div p (all <p> inside <div>) |
| Child | > | Selects direct children only. | ul > li (only <li> directly under <ul>) |
| Adjacent Sibling | + | Selects the immediately next sibling element. | h1 + p (first <p> right after <h1>) |
| General Sibling | ~ | Selects all siblings after an element. | h1 ~ p (all <p> siblings after <h1>) |
Examples
1. Descendant combinator (space)
div p { color: blue;}Selects all
<p>inside any<div>, no matter how deep.
2. Child combinator (>)
ul > li { font-weight: bold;}Selects only
<li>elements that are direct children of a<ul>.
3. Adjacent sibling combinator (+)
h2 + p { margin-top: 0;}Selects the first
<p>immediately following an<h2>.
4. General sibling combinator (~)
h2 ~ p { color: gray;}Selects all
<p>elements that are siblings after an<h2>.
Summary Table
| Selector | Matches |
|---|---|
A B | Any descendant B inside A |
A > B | Direct child B of A |
A + B | Next sibling B immediately after A |
A ~ B | All siblings B after A |
Want me to help you with some practical selector combos or how to use these in real layouts?