Search code examples
cssreactjstransform

Side menu transform animations is not working properly when the hamburger menu is clicked


I am trying to create a side menu, and to achieve that I was using left: -100% and then when the hamburger button is pressed it animates to left: 0% but I came to know that this is not very efficient way. So I switched to transform: translateX(-100%). But it is not working as expected. Here is a screenshots.

enter image description here

CSS Code

.nav-text-links-content {
    position: absolute;
    display: flex;
    gap: 20px;
    flex-direction: column;
    width: 100%;
    height: 85vh;
    top: 5rem;
    -webkit-transform: translateX(-100%);
    transform: translateX(-100%);
    /* left: -100%; */
    opacity: 0;
    transition: transform 300ms linear;
  }

Here is the link for the full project codesandbox


Solution

  • translateX(-100%) translates the element to the left by its own width.

    To hide it initially therefore it needs to know where its initial left position is and then translate. No left setting has been given so it 'starts' from where it is.

    We need to position it to the left so include a left: 0 styling.

    .nav-text-links-content {
        position: absolute;
        display: flex;
        gap: 20px;
        flex-direction: column;
        width: 100%;
        height: 85vh;
        top: 5rem;
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
        /* left: -100%; */
        left: 0; /* ADDED */
        opacity: 0;
        transition: transform 300ms linear;
      }
    

    Just as an aside, although using translate can indeed be 'more efficient' in this instance efficiency may not matter so much as this is not a continuous animation but happens only when the user clicks the icon which is unlikely to be continuous but occasional.