Search code examples
cssanimationtranslate-animation

Burgermenu: Animation in CSS (Rotate and Transform of "two" lines)


I've been fiddling around with a small problem with an animation that I can't really figure out the problem to.

I have this perfectly working example from w3 schools, but my case is a little different. I am trying to have 2 visible lines in my burger menu, and they are both supposed to be a little smaller.

I have this working code.

The code that is causing me trouble is the following:

.change .bar1 {
  -webkit-transform: rotate(-45deg) translate(-9px, 6px);
  transform: rotate(-45deg) translate(-9px, 6px);
}

.change .bar3 {
  -webkit-transform: rotate(45deg) translate(-8px, -8px);
  transform: rotate(45deg) translate(-8px, -8px);
}

I have tried to change the translate statements with so many different numbers and I tried reading to figure out exactly what the translate-statements do when they are placed like they are after the rotate. I just can't figure out exactly how to make the two lines create a cross on their "starting" location (that is without moving to the right or left - too much)

My question is:

  • What does the translate statements do when they are placed like they are?
  • How could I figure out how to make my lines create a cross in their starting position?

I am basically looking for a good method to figure out my problem myself. But if a bright mind out there could supply me with my solution I wouldn't mind. :)


Solution

  • function myFunction(x) {
      x.classList.toggle("change");
    }
    .container {
      display: inline-block;
      cursor: pointer;
    }
    
    .bar1, .bar3 {
      width: 35px;
      height: 2px;
      background-color: #333;
      margin: 6px 0;
      transition: 0.4s;
    }
    
    .invis {
      width: 35px;
      height: 2px;
      margin: 6px 0;
    }
    
    
    .change .bar1 {
      -webkit-transform: rotate(-45deg) translate(-5px, 6px);
      transform: rotate(-45deg) translate(-5px, 6px);
    }
    
    .change .bar3 {
      -webkit-transform: rotate(45deg) translate(-5px, -6px);
      transform: rotate(45deg) translate(-5px, -6px);
    }
    <p>Click on the Menu Icon to transform it to "X":</p>
    <div class="container" onclick="myFunction(this)">
      <div class="bar1"></div>
      <div class="invis"></div>
      <div class="bar3"></div>
    </div>

    Should work.

    Those numbers are X and Y position. Because you removed the middle line, the position is a little off.

    • X: Should be same for both. Increase/decrease moves it either left or right.
    • Y: Should be opposite, so they form a nice cross.