A CSS selector can include multiple simple selectors, and between these selectors, combinators can be used.
There are four types of combinators in CSS:
- Descendant selector (space)
- Child selector (>)
- Adjacent sibling selector (+)
- General sibling selector (~)
Descendant Selector
The descendant selector matches all elements that are descendants of a specified element.
The following example selects all <p>
elements within the <div>
element having class .div1
.
<div class="div1">
<p>Paragraph 1</p>
<div class="div2">
<p>Paragrapg 2</p>
<p>Paragraph 3</p>
</div>
</div>
.div1 p {
background-color: lightgreen;
}
The preview of the above code is given below, where the CSS has been applied to all the child <p>
elements of the <div>
element having class .div1
.
Child Selector (>)
The child selector matches all elements that are direct children of a specified element.
<div class="div1">
<p>Paragraph 1</p>
<div class="div2">
<p>Paragrapg 2</p>
<p>Paragraph 3</p>
</div>
</div>
.div1 > p {
background-color: lightgreen;
}
The preview of the above code is given below, where the CSS has been applied to only the direct child <p>
element of the <div>
element having class .div1
.
Adjacent Sibling Selector (+)
The adjacent sibling selector is used to select an element that is directly placed after a specific element.
Sibling elements must share the same parent, and "adjacent" means "immediately following".
<div>
<p>Paragraph 1</p>
</div>
<p>Paragrapg 2</p>
<p>Paragraph 3</p>
div + p {
background-color: lightgreen;
}
The preview of the above code is given below, where the CSS has been applied to only the first <p>
element, which is the adjacent sibling of the <div>
element.
General Sibling Selector (~)
The general sibling selector selects all elements that are next siblings of a specified element.
<div>
<p>Paragraph 1</p>
</div>
<p>Paragrapg 2</p>
<p>Paragrapg 3</p>
div ~ p {
background-color: lightgreen;
}
The preview of the above code is given below, where the CSS has been applied to all the <p>
elements, which are the next siblings of the <div>
element.