Search code examples
cssbuttonhovercss-animations

Why isn't my button animation working in CSS?


`I follow youtube to build the Button Hover Animations, but it can't work. This button should have a color side from left to right and also change the text color when the cursor point to the button. In the hover part I put scaleX(1) can,t saw any changes, the button has display the color if I put 2 After I write the button.slide, my cursor didn't work when pointed to the button

button.slide::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
  background-color: var(--accent-color);
  transition: transform, 300ms ease-in-out;
  transform: scaleX(0);
  transform-origin: left;
}

button.slide:hover::before,
button.slide:focus::before {
  transform: scaleX(2);
}

button.slide {
  transition: color 300ms ease-in-out;
  z-index: -1;
}

button.slide:hover,
button.slide:focus {
  color: white;
}
<button class="slide">Button</button>


Solution

  • Is that what you want?

    button.slide::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: -1;
      background-color: var(--accent-color);
      transition: transform, 300ms ease-in-out;
      transform: scaleX(0);
      transform-origin: left;
    }
    
    button.slide:hover::before,
    button.slide:focus::before {
      /* The animation only needs to fill the button */
      transform: scaleX(1);
    }
    
    button.slide {
      /* Used to restrict the ::before element */
      position: relative;
      transition: color 300ms ease-in-out;
      /* hover cannot be triggered when zIndex is -1 */
      z-index: 1;
      --accent-color: red
    }
    
    button.slide:hover,
    button.slide:focus {
      color: white;
    }
    <button class="slide">Button</button>