Dagmara Lewandowska
Dagmara Lewandowska

Reputation: 5

CSS Transition doesn't work with hamburger button

I made a hamburger button and I'm trying to animate spans to create a cross.

My transition doesn't work and I don't know why... I found that sometimes transitions doesn't work on chrome so I've used webkit prefix but it didn't help :(

This is my HTML code:

<div class="main__box__nav__hamburger">
    <span class="line line1"></span>
    <span class="line line2"></span>
    <span class="line line3"></span>
</div>

CSS code:

.main__box__nav__hamburger {
  min-width: 30px;
  height: 20px;
  margin: 45px 10px;
  position: relative;
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}
.line {
  position: absolute;
  min-width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #000;
}
.line2 {
  top: 8px;
}
.line3 {
  top: 16px;
}
.main__box__nav__hamburger.close .line1 {
  transform: rotate(45deg);
  top: 50%;
}
.main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 {
  transform: rotate(-45deg);
  top: 50%;
}

Upvotes: 0

Views: 441

Answers (1)

Terry
Terry

Reputation: 66123

That is because you are applying the transition to the parent element (the hamburger itself), instead of to its children. Remember that transition is not inherited.

Move the transition property to the .line selector and it will work:

.line {
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}

See proof-of-concept below (I have added some minimal JS, so clicking on the hamburger will toggle the close class needed to visualize the transition):

var burger = document.querySelector('.main__box__nav__hamburger');

burger.addEventListener('click', function() {
  this.classList.toggle('close');
});
.main__box__nav__hamburger {
  min-width: 30px;
  height: 20px;
  margin: 45px 10px;
  position: relative;
}
.line {
  position: absolute;
  min-width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #000;
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}
.line2 {
  top: 8px;
}
.line3 {
  top: 16px;
}
.main__box__nav__hamburger.close .line1 {
  transform: rotate(45deg);
  top: 50%;
}
.main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 {
  transform: rotate(-45deg);
  top: 50%;
}
<div class="main__box__nav__hamburger">
    <span class="line line1"></span>
    <span class="line line2"></span>
    <span class="line line3"></span>
</div>

Upvotes: 2

Related Questions