csscss-animationscss-transitionscss-transformsstylus

CSS transition & transform from hamburger bars --> X on click (using stylus)


i have a menu hamburger "icon" for the mobile breakpoint. i have it set up as 3 lines and i want them to transition to an X (that will close the menu).

i want the top bar to go 45 degrees, the middle bar to disappear, and the bottom bar to go 45 degrees the other way. then the top and bottom bars will shift up and create an X

AS OF NOW....it only animates for as long as i hold my mouse down. Why is this so? I just need the animation to complete itself on click.

html:

<a class="navbar-item-link" "javascript:void(0)" >
    <div class="hamburger-icon"><span></span></div>
</a>

stylus:

.hamburger-icon
    &:before, &.hamburger-icon span, &:after
    content ''
    display block
    height 2px
    width 20px
    background-size 100%
    background rgba(255,255,255,0.5)
    margin 6px auto 7px auto
    transition all 0.2s linear

    &:active
        &.hamburger-icon span
            background-color transparent
        &:before
            transform rotate(45deg)
            top -10px
            height 2px
            background rgba(255,255,255,0.5)
            width 30px
        &:after
            transform rotate(-45deg)
            bottom -10px
            height 2px
            background rgba(255,255,255,0.5)
            width 30px

Solution

  • The :active acts like a mouse down. When you'll release the click, the animation will stop.

    You have a few solutions using JS or CSS.

    In CSS, you could use the keyframes to be sure your animation will be finished.

    In JS, you could use a click event which could animate your icon with JS animations, or add a class which would contain your clicked properties.


    The following example is using a preprocessor. LESS or SASS would have the same syntax here:

    .hamburger-icon {
        /* .hamburger-icon styles */
        &.active {
            span {
                background-color: transparent;
            }
            &:before {
                transform: rotate(45deg);
                top: -10px;
                height: 2px;
                background: rgba(255,255,255,0.5);
                width: 30px;
            }
            &:after {
                transform: rotate(-45deg);
                bottom: -10px;
                height: 2px;
                background: rgba(255,255,255,0.5);
                width: 30px;
            }
        }
    }
    

    Then in jQuery

    $('.hamburger-icon').on('click', function(){
       $(this).addClass('active'); 
    });