CSS Combinator Selectors
CSS Combinator Selectors
| | Combinator selectors describe the relationship between two selectors. | | --- | --- |
CSS combinator selectors include various combinations of simple selectors.
In CSS3, there are four types of combinators:
- Descendant selector (separated by a space
)
- Child selector (separated by a greater than
>
sign) - Adjacent sibling selector (separated by a plus
+
sign) - General sibling selector (separated by a tilde
~
sign)
Descendant Selector
The descendant selector is used to select elements that are descendants of a specified element.
The following example selects all <p>
elements inside <div>
elements:
Example
div p {
background-color: yellow;
}
Child Selector
Compared to the descendant selector, the child selector only selects elements that are direct/first-level children of a specified element.
The following example selects all direct child <p>
elements of <div>
elements:
Example
div > p {
background-color: yellow;
}
Adjacent Sibling Selector
The adjacent sibling selector can select an element that is immediately following another element, both having the same parent.
If you need to select an element that is immediately following another element, and both have the same parent, you can use the adjacent sibling selector.
The following example selects the first <p>
element that is immediately after <div>
elements:
Example
div + p {
background-color: yellow;
}
General Sibling Selector
The general sibling selector selects all sibling elements that follow the specified element.
The following example selects all <p>
elements that are siblings following <div>
elements:
Example
div ~ p {
background-color: yellow;
}