More Web Design Tutorials

CSS3 – Transforms – 2D

December 28, 2012

Transform is yet another cool, new toy for our webdesign toy chest. Gone are the days of having to use a graphics editor to create certain effects. Now we can turn, spin, stretch, scale, and move things around with the CSS ‘transform’ property alone.

This box for example …

… can be turned onto its corner with just a little bit of CSS.

Check this out

But I’m getting ahead of myself.

Anyway, the new CSS3 property of ‘transform’ lets us change the shape of an element as well as its size, angle, and/or position. It is supported by the major newer browsers – with prefix, as follows:

Browser Version
and up
prefix
Chrome 1 -webkit-
Firefox 3.6 -moz-
Internet Explorer 9 -ms-
Opera 1 -o-
Safari 1 -webkit-

The first red box in this tutorial does not have any transform property applied. Please use that as your baseline for all of the following examples.

The available transform methods are:

Rotate

The second box in this tutorial was rotated by 45 degrees. To give you a comparison, a rotation of 20 degrees looks like this:

A 20-degree rotation

and is created by this CSS:

{
transform: rotate(20deg);
-ms-transform: rotate(20deg);
-webkit-transform: rotate(20deg);
-o-transform: rotate(20deg);
-moz-transform: rotate(20deg);
}

Scale

The scale method offers several options: We can scale height and width via

transform: scale(width,height)
scale(2,.5)

This distorts things a bit, but I doubled the width and halved the height of our square 100px box. Also note that even so the division now only displays half as tall, it still takes up the actual 100px space. (I did not change the top margin).
Instead of affecting both dimensions at once, we can address each individually by:

{
transform: scaleX(#); /* width */ --- or
transform: scaleY(#); /* height */
}

… or we can achieve the same effect by:

{
transform: scale(0,#); -- or --
transform: scale(#,0);
}

Skew

This skews things along the X and/or Y axis. Same syntax as with ‘scale’; so either

{
transform: skew (Xdeg,Ydeg); --or --
transform: skewX(#deg}; -- or --
transform: skewY(#deg};
}
skewX(25deg)

Translate

This won’t help you if there’s a foreign language involved, but it will move an element either vertically, horizontally, or both. You’re probably familiar with the system by now:

{
transform: translate(Xpx,Ypx); --or --
transform: translateX(#px}; -- or --
transform: translateY(#px};
}

The last method available here is:

Matrix

‘matrix’ comes with SIX parameters. This is a method probably more geared towards mathematicians. Personally, I think I’ll stick to any of those mentioned above, but here it is:

{
transform: matrix(.5,0,.9,.2,-.8,.666);
}

creates

matrix(.5,0,.9,.2,-.8,.666)

Not sure what you’d do with this, but here you go 🙂