Applying >, ~, + and CSS Selectors

Ole Ersoy
2 min readJan 3, 2023

--

Image by Larisa Koshkina from Pixabay

Scenario

We wish to understand how to go about applying the ~, +, and > CSS Selectors.

Approach

The Stackblitz demo for the writeup is at the bottom of the article.

Child Combinator > Selector

Suppose we wish to select all the paragraph elements nested directly inside the section element, but ignore any paragraphs that are deeper within the content.

<section id="ccs">
<h1>Child Combinator ( > ) Selector</h1>
<p>Hello there!</p>
<p>Hello there!</p>
<p>Hello there!</p>
<div>
<p>Hello there!</p>
</div>
</section>

We can do that using the child combinator selector like this.

section#ccs > p {
color: blue;
}

Adjacent Sibling Combinator ( + ) Selector

Suppose we want to select the first paragraph only following the h1 element in the below content.

<section id="asc">
<h1>Adjacent Sibling Combinator ( + ) Selector</h1>
<p>Hello there!</p>
<p>Hello there!</p>
<p>Hello there!</p>
</section>

We can do that using the Adjacent Sibling Selector like this.

section#asc h1 + p {
color: blue;
}

Note that the p element must follow the h1 element for this to work. If there is another element separating the p element and the h1 element nothing will be selected.

    <section id="asc">
<h1>Adjacent Sibling Combinator ( + ) Selector</h1>
<div></div>
<p>Hello there!</p>
<p>Hello there!</p>
<p>Hello there!</p>
</section>

General Sibling Combinator ( ~ ) Selector

Suppose we wish to select all the p element within section that follow the h1 element, even if there are other elements separating the h1 and p elements.

    <section id="gsc">
<h1>General Sibling Combinator Selector</h1>
<div>
<p>Hello there!</p>
</div>
<p>Hello there!</p>
<p>Hello there!</p>
<p>Hello there!</p>
<div>
<p>Hello there!</p>
</div>
</section>

We can do that using the General Sibling Cominator Selector like this.

section#gsc h1 ~ p {
color: blue;
}

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet