Transforming a hamburger icon fails

2019-08-27 00:19发布

问题:

for some reason I can't make my hamburger icon work as expected. I have saw many ways of doing it but I can't figure out what's wrong with mine. this is the result I get:

I expect to get the 'X' of course.

.hamb span {
  background-color: black;
  width: 50px;
  height: 5px;
  display: block;
  margin-bottom: 10px;
  transition: 0.5s;
}

.hamb:hover span:nth-child(1) {
  transform: rotate(45deg);
}

.hamb:hover span:nth-child(3) {
  transform: rotate(-45deg);
}

.hamb:hover span:nth-child(2) {
  transform: translateX(30px);
  opacity: 0;
}

.hamb:hover {
  cursor: pointer;
}
<div class="nav-item icon">
  <div class="hamb"><span></span> <span></span> <span></span></div>
</div>

回答1:

You should add some translation to the first and last span:

.hamb {
 margin:10px;
}

.hamb span {
  background-color: black;
  width: 50px;
  height: 5px;
  display: block;
  margin-bottom: 10px;
  transition: 0.5s;
}

.hamb:hover span:nth-child(1) {
  transform: rotate(45deg) translateY(21px);
}
.hamb:hover span:nth-child(3) {
  transform: rotate(-45deg) translateY(-21px);
}
.hamb:hover span:nth-child(2) {
  transform: translateX(30px) ;
  opacity: 0;
}

.hamb:hover {
  cursor: pointer;
}
<div class="hamb">
 <span></span>
 <span></span>
 <span></span>
</div>



回答2:

Building on @TermaniAfif's nice answer, I find it nice if the middle line stays in place and X is center aligned:

.hamb span {
  background-color: black;
  width: 50px;
  height: 5px;
  display: block;
  margin-bottom: 10px;
  transition: 0.5s;
}

.hamb:hover span:nth-child(1) {
  transform: rotate(45deg) translateY(10px) translateX(11px);
}
.hamb:hover span:nth-child(3) {
  transform: rotate(-45deg) translateY(-10px) translateX(11px);
}
.hamb:hover span:nth-child(2) {
  opacity: 0;
}

.hamb:hover {
  cursor: pointer;
}
<div class="hamb">
 <span></span>
 <span></span>
 <span></span>
</div>