Learn everything you need to know about the Combinators Selectors in CSS
Before you check out those cool features, take a step back and inspect the CSS basics through my CSS Basic Selector post.
In this article we will take a look of the Combinators Selectors
Combinators Selectors
In the previous post we have seen how to target elements, classes, ids and attributes. Now let’s see how we can combine they
Descendant Combinator Selector
The (space) combinator selects elements that are descendants of the previuos one.
With this combinator we can follow the document tree with selectors.
You can create a more specific selector by combining multiple items to follow the document tree structure. For example, if you have a span
tag nested inside a p
tag, you can target that one without applying the style to a span
tag not included in a p
tag
<span>
Hello!
</span>
<p>
My username is:
<span class="name">
DevToncho
</span>
</p>
p span {
color: yellow;
}
See how we used a space between the two type selectors p
and span
.
This works even if the element on the right is multiple levels deep.
Child Combinator Selector
The >
combinator selects elemtns that are direct children of the previous element.
With this combinator we can make a dependency strict on the first level by using the >
symbol between the two selectors
p > span {
color: yellow;
}
In this case, if a span
is not a first children of the p
element, it’s not going to have the new color applied.
Direct children will have the style applied:
<p>
<span>
This is yellow
</span>
<strong>
<span>
This is not yellow
</span>
</strong>
</p>
General Sibling Combinator Selector
The ~
combinator selects siblings elements. This means that the elements that follows the first, and both share the same parent
The General Sibling Selector allow us to style an element only if preceded by a specific element.
We can do it by using the ~
operator
p ~ span {
color: yellow;
}
This will assign the color yellow to all span
elements preceded by a p
element:
<p>This is a paragraph</p>
<span>This is a yellow span</span>
<span>This is another yellow span</span>
<span>This is another yellow span</span>
Adjacent Sibling Combinator Selector
The +
combinator selects adjacent siblings elemtns. This means that the second element directly follows the first, and both share the same parent.
The Adjacent sibling selectors let us style an element only if preceded by a specific element.
We can do it by using the +
operator
Example:
p + span {
color: yellow;
}
This will assign the color yellow to the next span
elements preceded by a p
element:
<p>This is a paragraph</p>
<span>This is a yellow span</span>
<span>This is not a yellow span</span>
<span>This is not a yellow span</span>