Using CSS Pseudo-Class + Sibling Selectors

Before diving in the tips and tricks using Pseudo-class and adjacent sibling, let’s understand first the Pseudo-Class.

Pseudo class selectors are CSS selectors with colon preceding them.

This is the popular one:

a:hover { // Yep, hover is a pseudo class 
  color: #fafafa;
}

Here’s the other pseudo-class :visited, :active, :focus, :checked, :first-child, :last-child and many more, you can check here. You have now the idea, right?

Now, for the Sibling Selectors, the Adjacent sibling combinator +, separates two elements or selectors and target preceded selector or element.

Example
<div>
    <ul>
    <li>This is the first list</li>
    <li>This is the first list</li>
    <li>This is the first list</li>
    </ul>
    <ul> <!-- Change color of li -->
    <li>This is the second list</li>
    <li>This is the second list</li>
    <li>This is the second list</li>
    </ul>
</div>
div ul + ul li{
    color: red;
}

While the General Adjacent Symbol, ~ it target all specific element preceded by the selector, separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Example:
<div>
    <ul>
        <li>This is the first list</li>
        <li>This is the first list</li>
        <li>This is the first list</li>
    </ul>
    <span>This is span</span>
    <ul> <!-- Target li -->
        <li>This is the second list</li>
        <li>This is the second list</li>
        <li>This is the second list</li>
    </ul>
    <ul> <!-- Target li -->
        <li>This is the third list</li>
        <li>This is the third list</li>
        <li>This is the third list</li>
    </ul>
</div>
div span ~ ul li{
    color: red;
}

Now, we understand how Pseudo Class and Sibling Selectors works. We can actually combine it to target complex elements.

Example

Output

HTML

<div>
    <div>
        <div class="button">Hover me</div>
        <div class="button">I will hide if you hover <<<</div>
    </div>
</div>

CSS

.button{
    background: #00cec9;
    display: inline-block;
    padding: 15px 30px;
    border-radius:4px;
    color: #fff;
    transition: .4s;
}
.button:last-child{
    background-color: #ff7675;
    transition: .4s;
    opacity: 1;
}
.button:hover{
    cursor: pointer;
}
.button:hover:first-child{
    background: #00b894;
}
.container div div .button:hover + .button{
    opacity: 0;
}

Notice that we combine pseudo class :hover with adjacent sibling selector + to target the preceding button. HOORAY!

That’s it, hope you guys learn about Sibling Selectors and Pseudo Class.

Share this: