DEV Community

Fahad Bin Faiz
Fahad Bin Faiz

Posted on

CSS Combinators

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>
Enter fullscreen mode Exit fullscreen mode
/* This is descendant combinator example */
.box p {
    color: red;
}  
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
/* this is child combinator example */
ul > li {
    border-top: 5px solid red;
} 
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
/* this is adjacent sibling combinator example */
h1 + p {
    font-weight: bold;
    background-color: #333;
    color: #fff;
    padding: .5em;
} 
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
/* this is general sibling combinator example*/
h1 ~ p {
    font-weight: bold;
    background-color: #333;
    color: #fff;
    padding: .5em;
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading...

Original article Click here

Top comments (0)