Simple animated carousel in CSS3 via keyframes

I had a little delve into CSS3 Animations to see if I could create a simple carousel. My first idea is to use keyframes. I’ll start with showing the result;
AnimExample

The idea is to infinitely fade between 3 elements.

<body>
    <div class="a isanim">AAAA</div>
    <div class="b isanim">BBBB</div>
    <div class="c isanim">CCCC</div>
</body>

The core style is;

 div.isanim {
            width:  250px;
            height: 250px;
            border: 3px solid black;
            position: absolute;            
            animation-duration: 18s;
            animation-direction: normal;
            animation-iteration-count: infinite;            
            display: block;
            opacity: 0
        }

What that says is we’re going to run an animation for a total of 18 seconds and then repeat it infinite times. Easy enough. Now for the bit that I didn’t think was too obvious;

        div.a {            
            animation-name: ani1;
            animation-delay: 0s;         
        }

        div.b {
            animation-name: ani2;
            animation-delay: 6s;            
        }

        div.c {
            animation-name: ani3;
            animation-delay: 12s;            
        }

We overwrite the core animation by providing specific details. The one I think is strange is that animation-delay is within the overall animation time. I.e. we’ve defined three animations all taking 18 seconds in total INCLUDING the delay. Is that correct? Is it, honestly I’m asking (?). Anyway with that in mind we can set up the keyframes;

        @keyframes ani1 {
            33% {
                background: green;
                opacity: 1;               
            }

            66% {
                display: none;
                opacity: 0
            }
        }

        @keyframes ani2 {
            0% {
                display: none;
                opacity: 0
            }

            33% {
                display: block;
                opacity: 1;
                background: red;
            }

            66% {
                display: none;
                opacity: 0;
            }           
        }

        @keyframes ani3 {
            0% {
                display: none;
                opacity: 0                
            }

            33% {
                display: block;
                opacity: 1;
                background: yellow;
            }

            66% {
                display: none;
                opacity: 0
            }           
        }

Since each animation has a proportional delay, the keyframes can all use the same % start. So after 33% they show themselves and after 66% they should have hidden themselves. I found these proportions worked better than 100% as that created too much of a clash of colours. One gotcha seems to be the 0% keyframe rule. If you don’t set that up you can get a strange ‘jumping’ effect.

Advertisements