Combinators

suggest change

Overview

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 target elements that come after them in the source document. CSS, by its nature (it cascades), cannot target previous or parent elements. However, using the flex order property, a previous sibling selector can be simulated on visual media.

Descendant Combinator: selector selector

A descendant combinator, represented by at least one space character (``), selects elements that are a descendant 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>

Live Demo on JSBin

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>

Live Demo on JSBin

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 immediate 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>

Live Demo on JSBin

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>

Live Demo on JSBin

The above example selects all <p> elements that are preceded by another <p> element, whether or not they are immediately adjacent.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents