Combinators
suggest changeOverview
Selector | Description |
—————–– | ———– |div span | Descendant selector (all <span>s that are descendants of a <div>) |div > span | Child selector (all <span>s that are a direct child of a <div>) |a ~ span | General Sibling selector (all <span>s that are siblings after an <a>) |a + span | Adjacent Sibling selector (all <span>s that are immediately after an <a>) |
Note: Sibling selectors match elements that follow them in the source document. They cannot match a previous sibling or a parent. The
orderproperty changes only visual order; it does not change which element a selector matches.
Descendant Combinator: selector selector
A descendant combinator, represented by one or more space characters, selects elements that are descendants of the defined element. This combinator selects all descendants of the element (from child elements on down).
div p {
color:red;
}
<div>
<p>My text is red</p>
<section>
<p>My text is red</p>
</section>
</div>
<p>My text is not red</p>
In the above example, the first two <p> elements are selected since they are both descendants of the <div>.
Child Combinator: selector > selector
The child (\>) combinator is used to select elements that are children, or direct descendants, of the specified element.
div > p {
color:red;
}
<div>
<p>My text is red</p>
<section>
<p>My text is not red</p>
</section>
</div>
The above CSS selects only the first <p> element, as it is the only paragraph directly descended from a <div>.
The second <p> element is not selected because it is not a direct child of the <div>.
Adjacent Sibling Combinator: selector + selector
The adjacent sibling (+) combinator selects a sibling element that immediately follows a specified element.
p + p {
color:red;
}
<p>My text is not red</p>
<p>My text is red</p>
<p>My text is red</p>
<hr>
<p>My text is not red</p>
The above example selects only those <p> elements which are directly preceded by another <p> element.
General Sibling Combinator: selector ~ selector
The general sibling (~) combinator selects all siblings that follow the specified element.
p ~ p {
color:red;
}
<p>My text is not red</p>
<p>My text is red</p>
<hr>
<h1>And now a title</h1>
<p>My text is red</p>
The above example selects all <p> elements that are preceded by another <p> element, whether or not they are immediately adjacent.