What is the best way to continuously loop a CSS animation that has multiple keyframe definitions?

Exploring the Challenge

In my coding journey, I encountered an interesting dilemma involving two css keyframe animations operating on a single element:

.fade-bg {
  animation-name: fade-bg-1, fade-bg-2;
  animation-delay: 0, 6s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

The description of the animations is as follows:

@keyframes fade-bg-1 {

  from {
      opacity: 0;
      background-image: url(image-1.jpg);
  }

  50% {
      opacity: 1;
      background-image: url(image-1.jpg);
  }

  to {
      opacity: 0;
      background-image: url(image-1.jpg);
  }

}

@keyframes fade-bg-2 { /* Similar to fade-bg-1 but with image-2.jpg */ }

While this setup technically works, it encounters a roadblock where upon reaching the second animation, it continuously replays that particular animation without circling back to fade-bg-1.

Various attempts at manipulating animation-direction have been made, yet none have yielded the desired outcome.

Pondering the Solution

I am left wondering: How can I configure the animation to return to fade-bg-1 and restart the looping process?

An Illustrative Scenario

EXAMPLE

Answer №1

To accomplish this effect without using javascript, you can utilize a single keyframe animation.

.fade-background {
  animation-name: fade-background;
  animation-delay: 0;
  animation-iteration-count: infinite;
  animation-direction: forward;
}

@keyframes fade-background {
    0% {
        opacity: 0;
        background-image: url('image-1.jpg');
    }

    25% {
        opacity: 1;
        background-image: url('image-1.jpg');
    }

    50% {
        opacity: 0;
        background-image: url('image-1.jpg');
    }

    51% {
        opacity: 0;
        background-image: url('image-2.jpg');
    }

    75% {
        opacity: 1;
        background-image: url('image-2.jpg');
    }

    100% {
        opacity: 0;
        background-image: url('image-2.jpg');
    }
}

VIEW EXAMPLE

Answer №2

It may not be achievable using only css, but by cleverly setting up a setInterval method in JavaScript, you could potentially mimic the same effect by dividing the class into two.

var index = 1;

function switchBackground() {
   if (index == 1) {
      //this changes to the first background
      var div = document.getElementById("yourDiv");
      div.className = "fade-bg-1";
      index = 0;
   }
   else {
      //this switches to the second background
      var div = document.getElementById("yourDiv");
      div.className = "fade-bg-2";
      index = 1;
   }
}

setInterval(switchBackground(), 6000);

Using .fade-bg-1 and .fade-bg-2 as the two animation classes.

Feel free to experiment with it on this jsfiddle.

Answer №3

It's been almost 6 years since I posted this question, and while things have changed, a pure CSS solution still seems elusive.

The closest workaround I could find involved using a pseudo element to apply the second animation.

Possible Solution:

To implement the second animation, consider utilizing a pseudo element like ::after.

Code:

.animation--fade-bg, .animation--fade-bg::after {
  width: 500px;
  height: 500px;
  background-size: cover;
  background-position: 50%;
  background-repeat: no-repeat;
  
  animation-iteration-count: infinite;
  animation-duration: 3s;
}

.animation--fade-bg::after {
  content: "";
  display: block;

  animation-direction: reverse;
}

.animation--fade-bg-1 {
  animation-name: fade-bg-1;

}

.animation--fade-bg::after {
  animation-name: fade-bg-2;
}


@keyframes fade-bg-1 {
  from {
    opacity: 0;
    background-image: url('http://i.imgur.com/sRnvs0K.jpg');
  }
    
  50% {
    opacity: 1;
    background-image: url('http://i.imgur.com/sRnvs0K.jpg');
  }   
     
  to {
    opacity: 0;
    background-image: url('http://i.imgur.com/sRnvs0K.jpg');
  }
}

@keyframes fade-bg-2 {
  from {
    opacity: 0;
    background-image: url('http://i.imgur.com/wL4RT1w.jpg');
  }

  50% {
    opacity: 1;
    background-image: url('http://i.imgur.com/wL4RT1w.jpg');
  }

  to {
    opacity: 0;
    background-image: url('http://i.imgur.com/wL4RT1w.jpg');
  }
}
<div class="animation--fade-bg animation--fade-bg-1"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to view the HTML division

I am struggling with my website creation as I encounter issues with the .Main div. Despite setting background-color: orange; in the CSS, the color is not visible on the page. The inspector shows that it is positioned at 1440 x 0. Any assistance would be gr ...

When hovering or mousing over, the text remains stationary and does not follow the scroll bar movement within the

A method I am using involves displaying additional data on hover for a shortened header, like this: Hover behavior However, the text shifts across the page when the scrollbar is used, as shown here: Scrollbar interaction This table showcases HTML, CSS, ...

consistent height across the div when expanding

There is a recurring issue I encounter where it takes too long for me to solve the problem. My goal is to ensure that the bootstrap boxes at the bottom of the page have the same height. I attempted to set a fixed height in pixels using my CSS, but this cau ...

Determining the condition of the menu: understanding whether it is open or closed

I'm diving into the world of jQuery and JavaScript, trying to grasp the ins and outs of the mmenu API. Despite my efforts to understand the libraries, the JavaScript code remains a mystery to me. Following the tutorial provided on , I successfully cr ...

Discovering the dimensions of a div for a mobile browser

I'm in the process of replicating the layout found at using HTML5 and CSS3, but I'm encountering an issue with the height. I've measured the footer's height to be 50px. While it displays fine on desktop browsers, it appears significant ...

"Efficiently incorporating a responsive sprite background image on your website -

Hey there! I am dealing with a situation where I have two columns of content in a container. The first column contains text, and the second column is a span with a background sprite image. The issue arises when the screen resolution gets smaller - I want ...

simultaneous image hover effect for all images

I am experiencing an issue with my CSS and Bootstrap hover effect. The overlay tags are enclosed within a div class, but they all hover simultaneously. Each overlay belongs to a different Bootstrap grid, yet the effect extends even to the empty spaces betw ...

Navigating the Drift

I am a beginner in HTML/CSS and need some assistance. Here is the layout I am working with: <style> #main {background-color: red; width: 30%;} #right_al{float: right;} #to_scroll{overflow: scroll;} </style> <div id='main'> ...

An unusual visual anomaly (a small line appears) when hovering over a button in the web browser

There is a peculiar issue with some buttons on a web page where a strange line appears on the right side when hovering over the button. This problem only affects the first two out of three buttons, possibly because there is no fourth button to trigger the ...

Looking for a logo placed in the center with a top fixed navigation using Bootstrap

I am in need of a Centered Logo using Bootstrap fixed top navigation. The goal is to have the brand centered within the navigation. Check out my Sample Fiddle .LandPageNavLinks { list-style-type:none; margin:0; padding:0; } .LandPageNavLin ...

Achieve equal height for two v-flex sections placed side by side in Vuetify framework

desired appearance: https://i.sstatic.net/aPrrP.png current appearance: https://i.sstatic.net/JNH2W.png In an attempt to ensure two tables have a consistent and responsive height using Vuetify features, I have implemented the following code: <templa ...

Is there a way to have my grid not apply grid-gap if a specific area is vacant?

I am working with a grid layout that has defined grid areas and a grid-gap, but some areas may not always have content. How can I prevent a double gap between items when an area is empty without changing the grid-template? For example: .grid { displa ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

Struggling to alter Material-UI theme styles

I have been working on a project using Material-UI and I am trying to change the default theme style of textTransform:"uppercase" to textTransform:"capitalize." After checking out the documentation on custom styling, I learned that I should use inline sty ...

Having trouble getting my image and text to align properly in two columns

<img id="story_image" src="images/builder_story_side.png" alt="photo"/> <div id="story_right"> <h2 class="story_header">fdgdfgdfgdfgdfgfdgdfgfdgdfgdfgdfgdfgdfgdfgdfgdfgdfgfdgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfg</h2> <p ...

When hovering over the label area, the entire rectangle will be highlighted

Could someone please assist with highlighting the entire row of the parent for the drop down feature? In the given scenario, level1 and level23 should be highlighted like the child items are. The goal is to highlight the entire row with the entire width. ...

Initiating change upon componentDidMount

Seeking advice on implementing a transition with react and css. The goal is to apply a class to the span element to achieve the desired animation effect – see illustration below. Curious to know whether the issue lies in the css implementation or the ja ...

CSS division nested within the center float division

In my attempt to design a 3-column home layout, I have successfully styled the center, left, and right sections. However, I am facing difficulty in placing two sliders within the middle class. My goal is to have slider1 positioned on top inside the middle ...

I tried to upload a unique theme on my WordPress website, but unfortunately, the design is not displaying correctly. I am having

After uploading a custom theme on WordPress as a parent theme, I encountered an issue where only simple text appeared on the screen without any styling, images, or sliders. Being new to PHP, I struggled to understand how to enqueue the styles in the functi ...

What steps can be taken to stop images from overflowing a flex-grow-1 item?

https://i.sstatic.net/1Qgec.pngHello, I'm facing an issue with my image. I am dealing with 3 sections: Main Content Image and other components (main section) Button Currently, I need to ensure that the image height is set to a maximum of 100% of the ...