Search code examples
htmlcssflexboxunderline

I m trying to make a sliding underline with css but its not working for some reason


Its a sign in and login form I am trying to build which switches to sign up as soon as i hover on the button. I expect the underline to move as soon as hover on the sign up button. Please tell me why the underline isnt sliding.

    #form{
        width: 300px;
        margin: auto;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    .butts{
        display: flex;
        justify-content: center;
    }
    
    #form .butt{
        width: 150px;
        height: 50px;
        font-size: 25px;
        display: inline-block;
    
    }
    
    
    hr{
        height: .25rem;
        width: 150px;
        margin: 0;
        background: tomato;
        border: none;
        transition: 1s ease-in-out;
    }
    
    #butt2:hover ~ hr{
        margin-left: 10px;
    }
    <section id="form">
        <div class="butts">
            <button class="butt" id="butt1">Login</button>
            <button class="butt" id="butt2">Sign Up</button>
        </div>
        <hr/>
    </section>


Solution

  • Your code does not works because, Css selector does not works for the higher node. "~" works only for adjacent element but here "hr" tag is adjacent to .butts class. Use below code to achieve what you are trying to achieve.

        #form{
            width: 300px;
            margin: auto;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        .butts{
            display: flex;
            justify-content: center;
            position: relative;
        }
        
        #form .butt{
            width: 150px;
            height: 50px;
            font-size: 25px;
            display: inline-block;
       }
        
        
        hr{
            height: .25rem;
            width: 150px;
            margin: 0;
            background: tomato;
            border: none;
            transition: 1s ease-in-out;
            position: absolute; 
            left: 0;
            bottom: 0;
        }
        
        #butt1:hover ~ hr{
            left: 0;
        }
        #butt2:hover ~ hr{
            left: 50%;
        }
        <section id="form">
            <div class="butts">
                <button class="butt" id="butt1">Login</button>
                <button class="butt" id="butt2">Sign Up</button>
    <hr/>
     
            </div>
                   </section>