CSS Combinators
CSS combinators include various ways to combine 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
~
)
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 a <div>
element:
div p {
background-color: yellow;
}
Child Selector
The child selector selects only the direct/first-level child elements of a specified element. The following example selects all direct child <p>
elements of a <div>
element:
div > p {
background-color: yellow;
}
Adjacent Sibling Selector
The adjacent sibling selector selects an element that is immediately preceded by a specified element, and both have the same parent. The following example selects the first <p>
element that is immediately after a <div>
element:
div + p {
background-color: yellow;
}
General Sibling Selector
The general sibling selector selects all elements that are siblings of a specified element and come after it. The following example selects all <p>
elements that are siblings of a <div>
element:
div ~ p {
background-color: yellow;
}