Pro CSS3 Animation

(Tuis.) #1

Chapter 6 ■ CSS3 Keyframe animationS for Web Content


In code, this is created using Listing 6-1, to which more markup will be added in further examples,

Listing 6-1. HTML Code for a Basic CSS3 Slideshow




Photograph of a Black kite
Profile of a Red kite
Pelicans on moorings at sea
Photograph of Pariah kite


In this example, you have four images at 400 pixels high by 500 pixels wide, so the total width of your inner
container must be 2000 pixels. (Note that all of the images must be the exact same size; the images in the example
shown are by Challiyil Eswaramangalath Pavithran Vipin, Ariful H Bhuiyan, Márcio Cabral de Moura, and Alan
Saunders, licensed under Creative Commons and used with permission).
The basic CSS, shown in Listing 6-2, is similarly straightforward:


Listing 6-2. Base CSS Code for a CSS3 Slideshow Image Gallery


div#slideshow { position: relative; background: #000; overflow: hidden; }
figure#imagestrip, div#slideshow { box-sizing: border-box; }
div#slideshow, figure#imagestrip img { width: 500px; height: 400px; float: left; }
figure#imagestrip { position: absolute; width: 2000px; margin: 0; }


To create the simplest slider animation you must move the inner figure horizontally in increments of 500
pixels, with a pause after each movement to allow the viewer time to appreciate each picture. As I discussed in
the previous chapter, CSS3 Animations do not work in explicit frames. You must treat the animation as a division
of time: for each image you designate an equal amount of time during which it will be still with the remaining
time designated for motion. In this example, each image will be still for 20% of the time, and the strip as a whole
will be in motion for 20% of the time, divided into four sequences. Thus each interstitial movement will take 5% of
the overall time.
The important part to remember when writing the keyframes is that properties you change must be present
as a set value between multiple keyframes if you wish to keep them the same; otherwise, the browser will revert
to interpolation using values you don’t wish it to use.
Your first attempt at the keyframe declaration might look something like Listing 6-3.


Listing 6-3. Keyframes for a Simple Image Slider


@keyframes slider {
0% { transform: translateX(0px); }
20% { transform: translateX(0px); }
25% { transform: translateX(−500px); }
45% { transform: translateX(−500px); }
50% { transform: translateX(−1000px); }
70% { transform: translateX(−1000px); }
75% { transform: translateX(−1500px); }
95% { transform: translateX(−1500px); }
100% { transform: translateX(−2000px); }
}

Free download pdf