Search code examples
htmlcsscss-animations

I want to start an image slideshow on hover with no weird transitions from one picture to the next using only CSS. How can I do it?


I want to start an image slideshow on hover with no weird transitions from one picture to the next using only CSS. I tried using the steps() function, which should work exactly as I described, but transitions happen nonetheless

How can I achieve my objective?

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  font-family: Arial, sans-serif;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

#image-slideshow {
  width: 300px;
  height: 200px;
  border: 3px solid black;
  border-radius: 5px;
  background: url("https://cdn.britannica.com/74/182174-050-6755AB49/balloon-sky.jpg") top/cover no-repeat;;
}

#image-slideshow:hover {
  animation: 5s steps(2) infinite slideshow;
}

@keyframes slideshow {
  33% {
    background: url("https://caloxinc.com/wp-content/uploads/2022/12/blog-blimp-helium-flying.jpg") top/cover no-repeat;
  }

  66% {
background: url("https://img.canarymedia.com/content/uploads/ZeroAvia-19-seat-prototype.jpg?auto=compress%2Cformat&crop=focalpoint&fit=crop&fp-x=0.5&fp-y=0.5&h=501&q=80&w=864&s=f1906dc9c8bd745878b612dfce20ad5c") top/cover no-repeat;
  }
}
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <h1>Slideshow on hover</h1>
    <div id="image-slideshow"></div>
  </body>
</html>

I examined multiple similar SO questions (1, 2, 3), but they don't appear helpful. For example, because they use JS (I can't use it here). If it turns out to be a duplicate, it's not because I was lazy


Solution

  • From what I understand, the number passed in steps() indicates the number of stops in the animation from 0% to 100%. For example, steps(2) will take 2 stops in the animation. At first step, it will add partial switch between images, and at second step, it will complete the switch. The bigger this number, the more steps it will take for the switch. This can be used to achieve smooth transition. Try setting that number to 100, and you will se more smooth transition between images. Setting this number to 1 means transition will happen at first step itself.