resizing span on hover first and second child

2019-07-24 02:15发布

问题:

What I am trying to do is my menu icon I want the top and mid span to move to the width specified when hovering with transition shrink from left to right. I dont want to use javascript so i am trying to accomplish it using css when i hover all the spans move to one size.

.menu-btn {
  width: 28px;
  position: absolute;
  left: 30px;
  height: 23px;
  top: 17px;
  display: block;
}

.menu-btn a {
  display: block;
}

.menu-btn span {
  display: block;
  height: 2px;
  background: #000;
  margin: 6px 0px;
}

.menu-btn:hover .menu-sandwhich:first-child {
  width: 17px;
}

.menu-btn:hover .menu-sandwhich:second-child {
  width: 23px;
}
<a href="" class="menu-btn">
  <span class="menu-sandwhich">
    	 <span></span>
        <span></span>
        <span></span>
  </span>
</a>

回答1:

You need to correct your code like this:

.menu-btn {
  width: 28px;
  position: absolute;
  left: 30px;
  height: 23px;
  top: 17px;
  display: block;
}

/*
not needed 
.menu-btn a {
  display: block;
}
*/
.menu-btn span {
  display: block;
  height: 2px;
  background: #000;
  margin: 6px 0px;
  margin-left:auto; /*so the shrink from left to right*/
  width: 100%;/*you need initial value*/
  transition: 1s all;/*Add this for transition*/
}


/* You need to apply to span the first-child*/
.menu-btn:hover .menu-sandwhich span:first-child {
  width: 17px;
}

.menu-btn:hover .menu-sandwhich span:nth-child(2) {/*there is no second-child*/
  width: 23px;
}
<a href="" class="menu-btn">
  <!-- use div to avoid conflict with CSS you apply to the span -->
  <div class="menu-sandwhich">
    <span></span>
    <span></span>
    <span></span>
  </div>
</a>

By the way, here is a better way to re-create your layout with less of code:

.menu-btn {
  width: 28px;
  position: absolute;
  left: 30px;
  height: 20px;
  top: 17px;
  display: block;
  background-image:
    linear-gradient(#000,#000),
    linear-gradient(#000,#000),
    linear-gradient(#000,#000);
  background-size:100% 2px;
  background-position:
     100% 0,
     100% 50%,
     100% 100%;
  background-repeat:no-repeat;
  transition:0.5s;
}

.menu-btn:hover {
  background-size:
    50% 2px,
    80% 2px,
    100% 2px;
}
<a href="#" class="menu-btn">

</a>