Felix DUSENGIMANA
Posted on May 16, 2022
When selecting HTML elements, sometimes it can be a little tricky to figure out which element you've selected. In this article, we'll provide an explanation of CSS combinators, making them easier to understand. Yeah, you've heard it, explained in an easy way.
CSS Combinators explains the relationship between CSS selectors, well I think you know what selectors are, if not consider reading this article. As the name says they combine different CSS selectors to provide useful relationships with each other.
Well, let's not take too long.
HTML code.
<div class="box">
<p>Text in box</p>
<section>
<p>Text in box inside section</p>
</section>
</div>
<div>
<h1>Heading inside div.</h1>
<p>Text in div not in box</p>
</div>
<p>Text 1 not both div and box</p>
<p>Text 2 not both div and box</p>
1. Descendant combinator
The descendant selector matches all elements that are descendants (children, grandchildren, and so on) of a specified element. We use space between selectors.
The following example selects all <p>
elements inside <div>
elements:
div p{
color: red;
}
2. Child combinator (>)
The child selector selects all elements that are direct descendants (children only) of a specified element. We use greater-than sign (>) between selectors.
The following example selects all <p>
elements that are children of a <div>
element:
div > p{
color: red;
}
Output:
3. Adjacent sibling combinator (+)
The adjacent sibling selector is used to select an element that immediately follows another specific element. Sibling elements must have the same parent element. We use plus sign (+) between selectors.
The following example selects the first <p>
element that are placed immediately after <div>
elements:
div + p{
color: red;
}
Output:
4. General sibling combinator (~)
The general sibling selector selects all elements that are next siblings of a specified element.
We use tilde sign (~) between selectors.
The following example selects all
elements that are next siblings of
elements:div ~ p{
color: red;
}
Output:
Let's connect:
Posted on May 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.