CSS Menu Icon Transformation Bug

时间:2017-04-10 00:00:58

标签: javascript html css3

I'm creating an animated menu icon using CSS transformations on a span and its :before and :after pseudo-elements.

When the menu icon transitions into the active state, the animation works perfectly. When the icon transitions back into its default state, the icon's middle bar pops back into existence between the other two bars. The additional pixels affect the positioning of the other two bars before the rotation transition occurs, making the animation awkward.

Can anyone think of a fix for this problem?

Here's the code:

document.querySelector("#nav-toggle").addEventListener("click", function() {
  this.classList.toggle("active");
});
#nav-toggle {
  display: block;
  width: 80px;
  padding: 0px 15px;
  line-height: 61px;
  color: #fff;
  background-color: #333;
  text-align: right;
}

#nav-toggle span {
  top: 36px;
}

#nav-toggle span,
#nav-toggle span:before,
#nav-toggle span:after {
  cursor: pointer;
  border-radius: 1px;
  height: 4px;
  width: 25px;
  background: white;
  position: absolute;
  display: block;
  content: '';
  transition: all 500ms ease-in-out;
}

#nav-toggle span:before {
  top: -8px;
}

#nav-toggle span:after {
  top: 8px;
}

#nav-toggle.active span {
  background-color: transparent;
  top: 36px;
}

#nav-toggle.active span:before,
#nav-toggle.active span:after {
  top: 0px;
}

#nav-toggle.active span:before {
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}

#nav-toggle.active span:after {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}
<body>
  <div>
    <a href="#" id="nav-toggle"><span></span>MENU</a>
  </div>
</body>

1 个答案:

答案 0 :(得分:1)

Change the code to

#nav-toggle span:before {
  top: -8px;
}

#nav-toggle span:after {
  top: 8px;
}