Home > front end >  Set width 100% to image in a animation
Set width 100% to image in a animation

Time:09-07

I am trying to create a image swapper using only css, with the animation feature I was able to easily able to make the images swap. However, due to the images themselves not being the perfect size, and using a div with a animation that changes background and sizing the div to fit the entire screen:

width: 100%;
height: auto;

to the images cannot be fitted in the screen like it is usually done with css if its done with the html img tag, therefore it creates various copies of the image to fill in the missing space.

How can I make the animation set the width of the images to 100%?

.animation {
    animation: imgswaper 10s infinite alternate;
    width: 100%;
    height: 300px;
}

@keyframes imgswaper {
    0% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
    1% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
    50% {
        background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
    }
    51%{
        background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
    }
    100% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div ></div>
  </body>
</html>

CodePudding user response:

Add background-size and background-repeat to your css. background-image is only discretely animatable though so it will look pretty janky.

More info here

.animation {
  animation: imgswaper 10s infinite alternate;
  width: 100%;
  height: 300px;
  background-size: contain;
  background-repeat: no-repeat;
}

@keyframes imgswaper {
  0% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
  1% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
  50% {
    background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
  }
  51% {
    background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
  }
  100% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" href="style.css" />
  <title>Document</title>
</head>

<body>
  <div ></div>
</body>

</html>

  • Related