Day 2 – GPU accelerate your DOM elements

First up, we have a super simple way to improve the performance of animating DOM elements. You probably know that in CSS3 you can move divs and images around in 3D space, and when you do this, some browsers render them using the graphics hardware.

So that’s fine for moving things in 3D but how often do you need to do that? Hardly ever! Mostly you move things in 2D, and browsers do that with the slow software renderer. Boring!

But you can fool the browsers into thinking they’re rendering in 3D by setting the z position to 0 using translateZ :

transform : translateZ(0);

And of course you should use the browser specific prefixes too, so use the following css to speed up moving rotating and scaling any div :

div {
	-webkit-transform : translateZ(0); 
	-o-transform : translateZ(0); 
	-moz-transform : translateZ(0); 
	transform : translateZ(0); 

And in an extremely rare case of my helping Mr.doob rather than the other way around, this is exactly how he improved the performance on Google Gravity.

The good news – this works really well in WebKit browsers (especially mobile Safari on iOS), the even better news is that FireFox will GPU accelerate anything with a transform, so you don’t even need this little hack.

You can find out more about CSS 3D transforms in our Burst game tutorial.

4 thoughts on “Day 2 – GPU accelerate your DOM elements

  1. Hey there,

    Shouldn’t the transform, without the browser prefixes, come last?

    Doesn’t really matter in this case, but still. I’ve always considered it to be best practice.


  2. One thing I’ve noticed with using translate3d in Safari is that there tends to be quite a bit of flickering of the element, and sometimes the element may disappear completely. Firefox and Chrome never seem to have this issue.

    For pretty much anything short of games on desktop, using top and left vs. translate has no noticeable difference in performance. On iPad, though, using translate3d offers huge performance gains that take a simple animation from choppy to butter smooth. It too seems to suffer from the same flickering issue, but seemingly less often.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *