CSS Wiping animation on exit

Viewed 887

I have an animation that wipes from left to right on hover here. I want to have an exit animation that also goes from left to right (not right to left as shown in the demo). How can I achieve this?

.btn {
  color: #31302B;
  background: #FFF;
  margin: 25px;
  padding: 10px 0;
  width: 240px;
  border: 3px solid #31302B;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 1px;
  text-transform: uppercase;
  border-radius: 2px;
  display: inline-block;
  text-align: center;
  cursor: pointer;
  box-shadow: inset 0 0 0 0 #6a0dad;
  -webkit-transition: all ease 0.8s;
  -moz-transition: all ease 0.8s;
  transition: all ease 0.8s;
}

.btn:hover {
  box-shadow: inset 240px 0 0 0 #6a0dad;
  color: #fff;
}
<div class="btn">CONTAINER</div>

3 Answers

You could use @keyframes:

.btn {
  color: #31302B;
  background: #FFF;
  margin: 25px;
  padding: 10px 0;
  width: 240px;
  border: 3px solid #31302B;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 1px;
  text-transform: uppercase;
  border-radius: 2px;
  display: inline-block;
  text-align: center;
  cursor: pointer;
  animation: out 0.8s ease;
}

@keyframes in {
  from {
    box-shadow: inset 0 0 0 0 #6a0dad;
    color: black;
  }
  to {
    box-shadow: inset 240px 0 0 0 #6a0dad;
    color: white;
  }
}

@keyframes out {
  from {
    box-shadow: inset -240px 0 0 0 #6a0dad;
    color: white;
  }
  to {
    box-shadow: inset 0 0 0 0 #6a0dad;
    color: black;
  }
}

.btn:hover {
  animation: in 0.8s ease;
  box-shadow: inset 240px 0 0 0 #6a0dad;
  color: white;
}
<div class="btn">CONTAINER</div>

I would suggest using pseudo-element ::after and transform-origin for this.

.btn::after {
    z-index: -1;
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    background: #6a0dad;
    height: 100%;
    width: 100%;
    transform: scaleX(0);
    transition: all ease 0.8s;
    transform-origin: left;
}
.btn:hover {
    color: white;
}
.btn:hover::after {
    transform: scaleX(1);
    transform-origin: right;
}

Add position: relative; z-index: 1; to .btn class

A simple background transition can easily do this without keyframes:

.btn {
  color: #31302B;
  background: #FFF;
  margin: 25px;
  padding: 10px 0;
  width: 240px;
  border: 3px solid #31302B;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 1px;
  text-transform: uppercase;
  border-radius: 2px;
  display: inline-block;
  text-align: center;
  cursor: pointer;
  background:linear-gradient(#6a0dad,#6a0dad) left/0% 100% no-repeat;
  transition: all ease 0.5s,background-position 0s 0.5s;
}

.btn:hover {
  background-size:100% 100%;
  background-position:right;
  color: #fff;
}
<div class="btn">CONTAINER</div>

Related: How to animate underline from left to right?

Related