html – CSS3 Smooth Animation To Change Background Image-ThrowExceptions

Exception or error:

I’m trying to change a background animation of a div using CSS animations, however, I am not able to make the transition smooth.

Any idea on how to do it? Here is my code.

.cover {
height: 200px;
width: 200px;
background-image: url('https://images.unsplash.com/photo-1582201943021-e8e5cb6dedc2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1562&q=80');

animation: mymove 5s;
animation-delay: 5s;
animation-timing-function: ease-in-out;
-webkit-animation-timing-function: ease-in-out;
}

@keyframes mymove {
  from {
      background-image: url('https://images.unsplash.com/photo-1582201943021-e8e5cb6dedc2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1562&q=80');
    }
  to {
    background-image: url('https://images.unsplash.com/photo-1582480356444-60ca00301659?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2001&q=80');
  }
<div class="cover">
</div>

What am I doing wrong here?

How to solve:

The normal background change has no animation. What you can do is the following:
You decrease the opacity of the background, change the background image and increase the opacity again. This will achieve a fade effect.

.cover {
height: 200px;
width: 200px;
background-image: url('https://images.unsplash.com/photo-1582201943021-e8e5cb6dedc2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1562&q=80');

animation: mymove 5s;
animation-delay: 5s;
animation-timing-function: ease-in-out;
-webkit-animation-timing-function: ease-in-out;
}

@keyframes mymove {
    0% { background-image: url('https://images.unsplash.com/photo-1582201943021-e8e5cb6dedc2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1562&q=80'); }
  50% { background-color:rgba(0, 0, 0, 0.5); }
  51% {     background-image: url('https://images.unsplash.com/photo-1582480356444-60ca00301659?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2001&q=80'); }
  100% { background-color:rgba(0, 0, 0, 1); }
<div class="cover">

</div>

###

I think the best option is to add a transition to your background image, so if you change it, there will be a animation. (In this example I used the :hover event)

.cover {
height: 200px;
width: 200px;
background-image: url('https://images.unsplash.com/photo-1582201943021-e8e5cb6dedc2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1562&q=80');

transition: background-image 5s ease-in-out;
}

.cover:hover{
  background-image: url('https://images.unsplash.com/photo-1582480356444-60ca00301659?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2001&q=80');
}
<div class="cover">

</div>

Leave a Reply

Your email address will not be published. Required fields are marked *