CSS Combinators
Fahad Bin Faiz
Posted on June 20, 2020
In this article, I will discuss CSS Combinators.
Table Of Contents
Descendant combinator
The descendant combinator — typically represented by a single space ( ) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector. Selectors that utilize a descendant combinator are called descendant selectors.
<div class="box">
<p>Text in .box</p>
</div>
<p>Text not in .box</p>
/* This is descendant combinator example */
.box p {
color: red;
}
Child combinator
The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Descendent elements further down the hierarchy don't match.
<ul>
<li>Unordered item</li>
<li>Unordered item
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>
</li>
</ul>
/* this is child combinator example */
ul > li {
border-top: 5px solid red;
}
Adjacent sibling combinator
The adjacent sibling selector (+) is used to select something if it is right next to another element at the same level of the hierarchy
<article>
<h1>A heading</h1>
<p>Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo
melon azuki bean garlic.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
</article>
/* this is adjacent sibling combinator example */
h1 + p {
font-weight: bold;
background-color: #333;
color: #fff;
padding: .5em;
}
General sibling combinator
If you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~). To select all img elements that come anywhere after p tag.
<article>
<h1>A heading</h1>
<p>I am a paragraph.</p>
<div>I am a div</div>
<p>I am another paragraph.</p>
</article>
/* this is general sibling combinator example*/
h1 ~ p {
font-weight: bold;
background-color: #333;
color: #fff;
padding: .5em;
}
Thanks for reading...
Original article Click here
Posted on June 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.