Search code examples
htmlcsscss-selectorspseudo-class

Target a class if a pseudo class of another sibling is triggered


I have this html:

<div class="header">
    <div class="active-tab-name"> Inbox </div>
        <form class="search-box" method="get" action="#">

            <input type="text" name="search_query" />

            <button class="icon-search"></button>

        </form> 
</div>

I need to change the property of the button when my input is focused : on input:focus with css. Here they are siblings and not nested. Is it possible?


Solution

  • If the button is the following sibling of the input (as in your example code), you can use the direct sibling selector + :

    input:focus + button{
        background:gold;
    }
    

    DEMO

    If the button is a sibling of the input but not directly after the input, you can use the general sibling selector ~ :

    input:focus ~ button{
        background:gold;
    }
    

    DEMO