Browser Support for CSS transitions
1.0
3.2
4.0
10
10.5
How to use transitions
If you haven't used transitions before, here's a brief introduction.
On the element you want to have animate, add the following CSS:
- #id_of_element {
- -webkit-transition: all 1s ease-in-out;
- -moz-transition: all 1s ease-in-out;
- -o-transition: all 1s ease-in-out;
- transition: all 1s ease-in-out;
- }
There is a lot of duplication due to vendor prefixes - until the specification if finalised, this will persist. If this bothers you, there are various tools such as CSS Scaffold, LESS, or my preference - SASS, that allow you to define mixins to avoid repetitive code.
Another approach is simply to write the CSS without the prefixes, then use Lea Verou's -prefix-free to add them in at runtime.
Something you definitely shouldn't do is to only include the webkit prefix. Tempting though it seems, particularly when developing for mobile devices, webkit isn't the only rendering engine!
It's worth noting as well that there isn't an
-ms-
prefix on these properties. IE10 was the first browser to ship without a prefix on these. The betas of IE10 did use the prefix however, so you may see code using -ms-
. It's not needed though.
The syntax is pretty straightforward, you specify the property you want to animate, all or border-radius or color or whatever, the time to run, then the transition timing function. The options for the timing function are shown below.
Whenever any property changes, then it will animate instead of changing directly. This can be due to a different set of properties set on a pseudo class such as hover, or a new class or properties set by javascript. The example below uses :hover to change the properties – no javascript is needed.
To see the difference in speed, have a look at the speed test.
Different timing functions
Ease
Ease
In
In
Ease
Out
Out
Ease
In Out
In Out
Linear
Custom
Awesome!
Hover on me
In addition to the built in timing functions, you can also specify your own. The excellent Ceaser CSS Easing Tool makes this very easy.
It's worth noting that the curves you produce can have negative values in them. The bezier curve for the last box above is
cubic-bezier(1.000, -0.530, 0.405, 1.425)
, the negative values are causing it to 'take a run up', which looks pretty awesome!Delays
The syntax for a CSS3 transition is of the form:
transition: [ <transition-property> || <transition-duration> || <transition-timing-function> || <transition-delay> ]
You will notice the final parameter is a delay - this let's you trigger things after an event has occurred. Below is a small demo showing this functionality.
Transition delays
Hover on me
This works by just adding a delay to each of the different circles. This is as easy as adding a
transition-delay: 0.6s;
to the element.Advanced delays
You can set the way different properties animate differently. In this example the normal (blue) circle has this CSS (with the appropriate vendor prefixes):
- #dd_main2 {
- transition: all 1s ease-in-out;
- }
The 'Example 1' (green) circle has this CSS instead:
- #dd_main2 {
- transition-property: top, left;
- transition-duration: 1s, 1s;
- transition-delay: 0s, 1s;
- }
While the 'Example 2' (red) circle has this CSS instead:
- #dd_main2 {
- transition-property: top, left, border-radius, background-color;
- transition-duration: 2s, 1s, 0.5s, 0.5s;
- transition-delay: 0s, 0.5s, 1s, 1.5s;
- }
This allows us to animate the properties independently of each other, meaning that this simple technique can be used to create very complex animations.
Normal
Example 1
Example 2
Hover on me
Animatable properties
Regarding the properties you can animate, the best way is to experiment. The W3C maintain a list of properties that can be animated on the CSS Transitions spec. These include everything from background-color and letter-spacing to text-shadow and min-height. Many of these properties are not supported by default by jQuery animation, making CSS transitions much more useful out of the box. In addition, many browsers hardware accelerate animations that don't require repaints, namely opacity, 3D transforms and filters. To see the methods that Webkit accelerates, take a look at the AnimationBase.cpp code from the Webkit source. At the time of writing there are three classes defined here:
PropertyWrapperAcceleratedOpacity
,PropertyWrapperAcceleratedTransform
and PropertyWrapperAcceleratedFilter
. These are the animations that Webkit accelerates. Other browsers do things differently, but as Webkit is popular on mobile where these things matter most, it's worth noting this special case.
In reality, browsers are allowing more properties than these to be animated -
box-shadow
springs to mind as an obvious example. The table below is taken from the link above, and can be considered the minimum number of properties you would expect to be animatable.Property Name | Type |
---|---|
background-color | color |
background-image | only gradients |
background-position | percentage, length |
border-bottom-color | color |
border-bottom-width | length |
border-color | color |
border-left-color | color |
border-left-width | length |
border-right-color | color |
border-right-width | length |
border-spacing | length |
border-top-color | color |
border-top-width | length |
border-width | length |
bottom | length, percentage |
color | color |
crop | rectangle |
font-size | length, percentage |
font-weight | number |
grid-* | various |
height | length, percentage |
left | length, percentage |
letter-spacing | length |
line-height | number, length, percentage |
margin-bottom | length |
margin-left | length |
margin-right | length |
margin-top | length |
max-height | length, percentage |
max-width | length, percentage |
min-height | length, percentage |
min-width | length, percentage |
opacity | number |
outline-color | color |
outline-offset | integer |
outline-width | length |
padding-bottom | length |
padding-left | length |
padding-right | length |
padding-top | length |
right | length, percentage |
text-indent | length, percentage |
text-shadow | shadow |
top | length, percentage |
vertical-align | keywords, length, percentage |
visibility | visibility |
width | length, percentage |
word-spacing | length, percentage |
z-index | integer |
zoom | number |
In addition to this, all browsers with transitions support animating CSS transforms, which proves to be invaluable.
To find out more about CSS3 transitions, read through the W3C specification.
Browser Support for 2D CSS Transforms
1.0
3.2
3.5
9
10.5
How to use transforms
There are two categories of transform - 2D transforms and 3D transforms. 2D transforms are more widely supported, whereas 3D transforms are only in newer browers.
2D examples
This div has been skewed - note that the text is still selectable.
This div has been scaled - again, the text is real text.
This div has been rotated - you get the idea about the text!
This div has been translated 10px down, and 20px across.
This div has all four types!
The code for these looks like this, but with the appropriate vendor prefixes added:
#skew { transform:skew(35deg); } #scale { transform:scale(1,0.5); } #rotate { transform:rotate(45deg); } #translate { transform:translate(10px, 20px); } #rotate-skew-scale-translate { transform:skew(30deg) scale(1.1,1.1) rotate(40deg) translate(10px, 20px); }
CSS transforms also be animated using transitions - try hovering on the div below.
Hover on me and I'll spin and scale!
CSS 3D Transforms
Browser Support for 3D CSS Transforms
12.0
4.0
10.0
10.0
-
3D CSS transforms are similar to 2D CSS transforms. The basic properties are
translate3d
, scale3d
, rotateX
, rotateY
androtateZ
. translate3d
and scale3d
take three arguments for x,y and z, whereas the rotates just take an angle. Here are some examples:
rotateX
rotateY
rotateZ
Hover me
The simplified code for those looks like this:
#transDemo4 div { transition:all 2s ease-in-out; perspective: 800px; perspective-origin: 50% 100px; } #transDemo4:hover #rotateX { transform:rotateX(180deg); } #transDemo4:hover #rotateY { transform:rotateY(180deg); } #transDemo4:hover #rotateZ { transform:rotateZ(180deg); }
A cube made with 3D CSS transforms
1
2
3
4
5
6
Have a play with the controls - there's no transition here, just the sliders to control it. Note that I'm only using javascript to update the css values - all the maths needed is done by the browser automatically.
A 3D image slider
Note that because of the way a cube works, the image is moved out towards the screen, and is bigger than it should be. You should move it back by half the width of an image to make sure it is normal size.
Image 1 Image 2 Image 3 Image 4
Click me to toggle transparency
3D transforms playground
Original
Transformed
For more information read both the Webkit blog entry from when 3D transforms were first implemented, David Desandro's awesome examples and Microsoft's 3D transforms test drive.
Advanced usage
Though it's rare that you'll need it, it's worth noting that the raw matrix implementations are exposed as well. As an example, the skew transform above has a skew of 35 degrees. To find the internal representation, you can use javascript to find the computed style. In this case,
skew(35deg)
is represented by matrix(1, 0, 0.7002075382097097, 1, 0, 0)
. The astute among you will note that this is a 2×3 matrix. To use them for normal arithmetic, add a third row of 0, 0, 1
.
CSS 3D transforms are represented similarly, with a 4×4 matrix.
Understanding how to create these matrices is probably out of the scope of this tutorial, but an undergraduate understanding of matrix algebra should suffice. Read the Wikipedia article on transformation matrices for a quick primer.
For the exact methods, read the part of the spec about 2D matrix decomposition and 3D matrix interface.
Demo 1 - One image to another, on hover
Plan
- Put one image on top of the other
- Change the opacity of the top image on hover
Demo
Code
First up, the HTML markup. Without CSS enabled, you just get two images. Remember to add alt text for production use.
<div id="cf"> <img class="bottom" src="/images/Windows%20Logo.jpg" /> <img class="top" src="/images/Turtle.jpg" /> </div>
Then the CSS:
#cf { position:relative; height:281px; width:450px; margin:0 auto; } #cf img { position:absolute; 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; } #cf img.top:hover { opacity:0; }
Demo 2 - One image to another, when a button is pressed (transitions)
Plan
Same as before, but instead of using the :hover pseudo class, we are going to use javascript to add a toggle a class. I'm using jQuery here because it's easy to understand, though you could just use plain old JS.
Demo
Click me to toggle
Code
First up, the HTML markup. Again, with no CSS enabled, you just get two images.
<div id="cf2" class="shadow"> <img class="bottom" src="/images/Windows%20Logo.jpg" /> <img class="top" src="/images/Turtle.jpg" /> </div> <p id="cf_onclick">Click me to toggle</p>
Then the CSS. I've added a class with the opacity value.
#cf2 { position:relative; height:281px; width:450px; margin:0 auto; } #cf2 img { position:absolute; 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; } #cf2 img.transparent { opacity:0; } #cf_onclick { cursor:pointer; }
Then the extremely short JS. Note that the browser is smart enough to realise that it can animate to the new properties, I didn't have to set them in javascript (thought that works too).
$(document).ready(function() { $("#cf_onclick").click(function() { $("#cf2 img.top").toggleClass("transparent"); }); });
Have a look at the multiple image demo to see how to extend this idea to more than two images.
Demo 3 - One image to another with a timer (CSS animations)
Plan
You could implement this by using Javascript to toggle classes with a delay - that would allow older browsers to still have the images change. As we are looking forward though, we'll use CSS keyframes.
- Start with two images absolutely positioned on top of each other.
- Use CSS keyframes to define two states, one with top image transparent, one with it opaque.
- Set the animations number of iterations to infinite.
Demo
Each image is visible for 9 seconds before fading to the other one.
Code
Everything's the same as Demo 1, but I've added this to the CSS and removed the hover selector
@keyframes cf3FadeInOut { 0% { opacity:1; } 45% { opacity:1; } 55% { opacity:0; } 100% { opacity:0; } } #cf3 img.top { animation-name: cf3FadeInOut; animation-timing-function: ease-in-out; animation-iteration-count: infinite; animation-duration: 10s; animation-direction: alternate; }
To make sense of that, I've defined 4 keyframes, specified that whatever has this animation attached will be opaque for the first 45%, then transparent for the last 45%. The animation will repeat forever, will last 10 seconds, and will run forward then backwards. In other words, image 1 will be visible for 4.5 seconds, followed by a 1 second fade, followed by 4.5 seconds of image 2 being visible. Then it will reverse, meaning that image 1 and 2 will both be visible for 9 (4.5 x 2) seconds each time.
Demo with multiple images
Staggering the animations can result in a multiple image fader.
This time I've created an animation that goes from 0 to 1 opacity, then staggered the animations so only one is visible at once.
Thanks to Pafson's comment, this is finally working as expected! He proposes the following algorithm to determine the percentages and timings:
For "n" images You must define:
a=presentation time for one image
b=duration for cross fading
Total animation-duration is of course t=(a+b)*n
animation-delay = t/n or = a+b
Percentage for keyframes:
a=presentation time for one image
b=duration for cross fading
Total animation-duration is of course t=(a+b)*n
animation-delay = t/n or = a+b
Percentage for keyframes:
- 0%
- a/t*100%
- (a+b)/t*100% = 1/n*100%
- 100%-(b/t*100%)
- 100%
@keyframes cf4FadeInOut { 0% { opacity:1; } 17% { opacity:1; } 25% { opacity:0; } 92% { opacity:0; } 100% { opacity:1; } } #cf4a img:nth-of-type(1) { animation-delay: 6s; } #cf4a img:nth-of-type(2) { animation-delay: 4s; } #cf4a img:nth-of-type(3) { animation-delay: 2s; } #cf4a img:nth-of-type(4) { animation-delay: 0; }
Demo 4 - More than just fades
This technique isn't limited to just fades, you can animate almost every property. Here are a couple of examples.
Zooming in and out
Hover on the image
Rotation
Hover on the image
Demo 5 - Animating the background-image property
Right now this only works on webkits built from 2012 onwards. It's not part of the spec (yet?).
Plan
- Make a div with a width and height
- Change the background-image property
Demo
Code
This only works on Chrome 18+ and on Webkit built in 2012 onwards, including iOS6. It seems to be a side effect of the CSS4 crossfading work, though this is a lot more useful.
<div id="cf6_image" class="shadow"></div>
Then the CSS:
#cf6_image { margin:0 auto; width:450px; height:281px; transition: background-image 1s ease-in-out; background-image:url("/images/Windows%20Logo.jpg"); } #cf6_image:hover { background-image:url("/images/Turtle.jpg"); }
Pretty cool - this can easily be extended by simply changing the background-image property with JS, and makes things much much simpler. I'm not sure if this behaviour is part of the spec or not, and I haven't seen support anywhere other than in the afore mentioned browsers.
For a slightly more detailed example, have a look at a simple gallery using filters and fades.
Demo 6 -Fading between multiple images on click
Image 1 Image 2 Image 3 Image 4
This is very similar to the others – just layout the images on top of each other, set them all to be transparent, then when the controls are clicked change that one to opaque.
For this example:
HTML
<div id="cf7" class="shadow"> <img class='opaque' src="/images/Windows%20Logo.jpg" /> <img src="/images/Turtle.jpg;" /> <img src="/images/Rainbow%20Worm.jpg;" /> <img src="/images/Birdman.jpg;" /> </div> <p id="cf7_controls"> <span class="selected">Image 1</span> <span>Image 2</span> <span>Image 3</span> <span>Image 4</span> </p>
CSS
p#cf7_controls { text-align:center; } #cf7_controls span { padding-right:2em; cursor:pointer; } #cf7 { position:relative; height:281px; width:450px; margin:0 auto 10px; } #cf7 img { position:absolute; 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; opacity:0; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); } #cf7 img.opaque { opacity:1; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: alpha(opacity=1); }
JS
$(document).ready(function() { $("#cf7_controls").on('click', 'span', function() { $("#cf7 img").removeClass("opaque"); var newImage = $(this).index(); $("#cf7 img").eq(newImage).addClass("opaque"); $("#cf7_controls span").removeClass("selected"); $(this).addClass("selected"); }); });
Flipping a simple image to a div (transitions and 3d transforms)
Plan
- Put an image on top of a div inside a container.
- Put that in another container with perspective defined.
- When hovering on the outside container, add a rotate around the Y axis to the inside container.
Demo
Code
First, the markup.
<div id="f1_container"> <div id="f1_card" class="shadow"> <div class="front face"> <img src="/images/Windows%20Logo.jpg"/> </div> <div class="back face center"> <p>This is nice for exposing more information about an image.</p> <p>Any content can go here.</p> </div> </div> </div>
Then the CSS, stripped of the vendor prefixes to keep it clean.
#f1_container { position: relative; margin: 10px auto; width: 450px; height: 281px; z-index: 1; } #f1_container { perspective: 1000; } #f1_card { width: 100%; height: 100%; transform-style: preserve-3d; transition: all 1.0s linear; } #f1_container:hover #f1_card { transform: rotateY(180deg); box-shadow: -5px 5px 5px #aaa; } .face { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; } .face.back { display: block; transform: rotateY(180deg); box-sizing: border-box; padding: 10px; color: white; text-align: center; background-color: #aaa; }
Flipping around other axes
You can also flip around the X and Z axes by changing
rotateY
to rotateX
or rotateZ
.Case Study: Flipping cards on the Southampton Hackney Association's Website
Part of the design for the Southampton Hackney Association included a grid of sponsors. The design was such that on hover or click, they would flip over revealing a contact number, email address or URL. We wanted this site to work on browsers that didn't support 3D transforms, as at the time, only webkit had support.
Code path for browsers with 3D transforms
The code used is exactly as above. The markup consists of a div, containing two divs for the back and front faces.
Fallback
In older browsers, jQuery Flip is used. Modernizr is used to detect support for 3D transforms and if not, the markup is altered to fit how jQuery flip requires it to be. The key part is that for normal browsers, normal 3D transforms are used, with none of the fluff required to get this to work.
Due to issues with getting jQuery flip to work on hover, the behaviour was changed to work on click.
Using this technique, the effect works on all browsers in use, back to IE6. The flip effect is of much higher quality on browsers that support 3D transforms, but still has the distinctive look and feel on older browsers. As we move forward, the percentage of users who hit the fallback will decrease
Accordions
Plan
- Mark up a few sections with a title and content
- Set the height to all but the first to 0, and overflow to hidden on all of them
- Bind click events using JS on the titles to change the heights
Demo
▶
A long paragraph
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus
▶
A medium paragraph
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
▶
Two short paragraphs
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.
Not sure if the use/abuse of Unicode is really a good idea, but you can see that it's pretty easy to get a simple accordion working.
I'm using classes again here to define different states, then using jQuery to turn them on and off. As always, I could use the :target pseudo selector, but I'd want to use preventDefault() onClick anyway to prevent the page skipping up and down, so I might as well just do it all in jQuery.
The Code
HTML:
<div id="accordion"> <section id="item1"> <p class="pointer">▶</p><h1><a href="#">A long paragraph</a></h1> <p>Pellentesque habitant... </p> </section> <section id="item2" class="ac_hidden"> <p class="pointer">▶</p><h1><a href="#">A medium paragraph</a></h1> <p>Pellentesque habitant... </p> </section> <section id="item3" class="ac_hidden"> <p class="pointer">▶</p><h1><a href="#">Two short paragraphs</a></h1> <p>Pellentesque habitant... </p> <p>Pellentesque habitant... </p> </section> </div>
CSS:
#accordion section, #accordion .pointer, #accordion h1, #accordion p { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -ms-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; } #accordion { margin-bottom:30px; } #accordion h1 { line-height:1.2; font-size:20px; background-color:rgba(255,0,0,0.3); margin:0; padding: 10px 10px 10px 30px; } #accordion h1 a { color:black; } #accordion section { overflow:hidden; height:220px; border:1px #333 solid; } #accordion p { padding:0 10px; color:black; } #accordion section.ac_hidden p:not(.pointer) { color:#fff; } #accordion section.ac_hidden { height:44px; } #accordion .pointer { padding:0; margin:10px 0 0 6px; line-height:20px; width:13px; position:absolute; } #accordion section:not(.ac_hidden) h1 { background-color:rgba(255,0,0,0.7); } #accordion section:not(.ac_hidden) .pointer { display:block; -webkit-transform:rotate(90deg); -moz-transform:rotate(90deg); -o-transform:rotate(90deg); transform:rotate(90deg); padding:0; }
Plus a bit of javascript to turn the classes on and off.
$(document).ready(function() { $("#accordion section h1").click(function(e) { $(this).parents().siblings("section").addClass("ac_hidden"); $(this).parents("section").removeClass("ac_hidden"); e.preventDefault(); }); });
With all these examples, no attempt has been made to hack around browsers with no support, other than adding the opacity filter in IE where appropriate. This ends up as two lines, as they changed it to a different incorrect syntax between versions 7 and 8.
In most cases, the transition happens, but with no animation - you see the beginning and end frames but nothing in between. Depending on the site, this may or may not be acceptable. Modernizr provides a nice feature detection library, allowing you to easily add different CSS/JS for legacy browsers.
The best way to do this in practice is to include Modernizr, then to use some javascript such as:
// We might as well bind to all the events, they just won't fire in the other browers.
var speed = 500,
transitionEndEvents = 'webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd transitionend';
function animate(object, cssProperties, callback, ms) {
if (!ms) {
ms = speed;
}
if (Modernizr.csstransitions) {
// jQuery 1.8+ deals with vendor prefixes for you.
object.css("transition", "all "+ms+"ms ease-in-out");
object.css(cssProperties);
if ($.isFunction(callback)) {
object.bind(transitionEndEvents,function(){
object.unbind(transitionEndEvents);
callback();
});
}
} else {
if ($.isFunction(callback)) {
object.animate(cssProperties, ms, callback);
} else {
object.animate(cssProperties, ms);
}
}
}
You can then use javascript to animate something and know that in modern browsers it will use a transition, while in older ones you get the jQuery animation. On the iPhone and iPad particularly this approach gets you much higher frame rates than just using the jQuery animate method.
If you are using simple properties, you can call it like this:
animate($("#someID"),{"left":"100px"});
For things where the property to be changed has the vendor prefix concatenated to it, use:
var cssArgs = {};
cssArgs[vP+"transform"] = "translate(100px,0px)";
animate($("#someID"),cssArgs);
If you are better at JS than me and can think of a way to make this less clumsy, please let me know!
No comments:
Post a Comment