CSS Combinators -
There's even more you can do with selectors. Combinators are used to select more specific elements, In other words -
Combinators explain the relationship with selectors -
NOw we will study different types of combinators -
1. 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).
Example -
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>
|
Output-
In the above example, the first two <p> elements are selected since they are both descendants of the <div>.
2. Child Combinator: selector > selector -
the child combinator matches an element that is a direct child of the element on the left hand side. It is specified with a > character:
.header > div
Matches all div elements that are direct children of an element with a class of header.
If those divs have children that are also divs, those divs will not be matched by the selector.
Example -
div > p {
color:red;
}
<div>
<p>My text is red</p>
<section>
<p>My text is not red</p>
</section>
</div>
|
Output -
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>.
3. Adjacent Sibling Combinator: selector + selector -
The adjacent sibling (+) combinator selects a sibling element that immediately follows a specified element.
Example -
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>
|
Output -
The above example selects only those <p> elements which are directly preceded by another <p> element.
4. General Sibling Combinator: selector ~ selector -
The general sibling (~) combinator selects all siblings that follow the specified element.
Example-
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>
|
Output -