Understanding use of the +, >, and ~ symbols in CSS selectors
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
A combinator is something that explains the relationship between the selectors.
There are four different combinators in CSS:
- Descendant Selector (space)
- Child Selector (>)
- Adjacent Sibling Selector (+)
- General Sibling Selector (~)
Let us see how we can use different symbols (+, >, and ~) in CSS selectors and their differences.
Let us start with an example HTML.
<div class="container">
<p>Apple</p>
<div>
<p>An apple a day keeps doctor away!</p>
</div>
<p>Banana</p>
<p>Cherry</p>
</div>
1. The Space
This is one of the most commonly used selector in CSS.
div.container p {
font-size: 20px;
}
As you can see in the code above, there is a space between div.container and p. It is called the Descendant selector. It will target all <p> tags within container div. That is, all <p> elements that are children of #container at any depth.
2. The ‘>’ Symbol
This is called the child selector. CSS rules will be applied to elements which are direct children of the particular element.
div.container > p {
border-bottom: 1px dashed black;
}
It will target (represented with a green dot in HTML image) all the <p> tags which are immediate children of container <div>, but the children of children will not be selected (represented with the red dot).
3. The ‘+’ Symbol
This is Adjacent Sibling Selector. It selects all elements that are the adjacent siblings of a specified element.
Sibling elements must have the same parent element, and “adjacent” means “immediately following”.
div + p {
background-color: yellow;
}
In our example, it will target to Banana only because the <p> tag comes just after the <div> tag.
4. The ‘~’ Symbol
It is General Sibling Selector and similar to Adjacent Sibling Selector. It selects all next elements that are siblings of a specified element.
The following example selects all next <p> elements that are siblings of <div> elements.
div ~ p {
background-color: yellow;
}
It will target Banana and Cherry <p> tags.
I hope you liked this refresher on CSS Combinators.
Liked my article? Coffee keeps me motivated, Buy me one! :P
— Aniket Kudale