Search code examples
csswordpressimagecross-fade

Image crossfading without HTML - ONLY CSS


I need help with a homework for Webdesign. We have to design a Wordpress-Page only using CSS. I want a crossfading in the header with 2 images.

Below the important part of my code. Of course it doesn´t work like this because of the two background-images. The animation is ready, but when the img fade out, there is only a white hole.

So how can I put 2 images in CSS?... Thank you for help! (And sorry for bad English :D)

#pageheader {
background-image: url('img/test.jpg');
background-image: url('img/bg.jpg');
height: 500px;
background-repeat: no-repeat;
background-position: center center;
background-size: 100% auto;

left:0;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}

@keyframes pageheaderFadeInOut {

0% {
opacity:1;
}

45% {
      opacity:1;
  }

55% {
    opacity:0;
    }

100% {
      opacity:0;
  }
}

#pageheader {
animation-name: pageheaderFadeInOut;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
animation-duration: 10s;
animation-direction: alternate;
}

Solution

  • You see that "white hole" when your animation runs because both your background images are inside your #pageheader div, which your animation is making transparent.

    Since you don't want to edit your HTML, we can use the :after pseudo-element to act as a separate element to hold your second image. Note that this won't work with more than these two images.

    Here's a working jsfiddle.

    CSS:
    #pageheader {
      background-image: url('img/test.jpg');
      height: 500px;
      width: 600px;
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
      -webkit-transition: opacity 1s ease-in-out;
      -moz-transition: opacity 1s ease-in-out;
      -o-transition: opacity 1s ease-in-out;
      transition: opacity 1s ease-in-out;
    }
    
    #pageheader:after{
      content: '';
      display: block;
      width: 100%;
      height: 500px;
      background-image: url('img/bg.jpg');
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
      animation-name: pageheaderFadeInOut;
      animation-timing-function: ease;
      animation-iteration-count: infinite;
      animation-duration: 10s;
     }
    
    
    @keyframes pageheaderFadeInOut {
      0% {opacity:1;}
      50% {opacity:0;}  
      100% {opacity:1;}
    }
    

    Note that you'll need to add browser prefixes (like I did in the jsfiddle).