So far I’ve covered CSS3 topics such how to make rounded corners, adding box shadows and using a custom font. Today I’m going to show you how you can transform DOM elements with the CSS “transform” property. Using this property, you can rotate, scale, skew and translate elements and images.
The “translate” transform moves the element horizontally X and vertically Y distances using the top left corner as the reference point (and yes, for the near future, you’re going to need to include the “-moz” and “-webkit” versions as well since the CSS3 property isn’t fully implemented in all browsers yet). Make sure when specifying distances you include a unit of measure (ie – “px”, “em”, etc.) because the transformation won’t work if you just specify a number. Additionally, you can use the “translateX(<value>)” or “translateY(<value>)” if you only want to translate on a single axis.
-webkit-transform: translate(40px,10px) rotate(40deg);
-moz-transform: translate(40px,10px) rotate(40deg);
transform: translate(40px,10px) rotate(40deg);
-webkit-transform: rotate(40deg) translate(40px,10px);
-moz-transform: rotate(40deg) translate(40px,10px);
transform: rotate(40deg) translate(40px,10px);
Using the “rotate” transform, we can rotate the element by X degrees. In the above example we’re chaining a transform with a rotate to achieve two effects. Any rotation to the element also rotates the X and Y axises of the element. This is a big deal because the order of the transform effects matters. Take a look at the two examples where we translate and rotate an element by the same amounts only in the first example we put the translate first and in the second example we put the rotate first.
Scaling and Skewing too!
-webkit-transform: translate(50px,30px) scale(1.5,1.8) skewX(20deg);
-moz-transform: translate(50px,30px) scale(1.5,1.8) skewX(20deg);
transform: translate(50px,30px) scale(1.5,1.8) skewX(20deg);
There are two more transform effects, scale and skew. The “scale” effect accepts floating-point values greater or equal to zero for both the X and Y axises. The number represents the percentage the width and/or height should be multiplied by. For example, if we have a width of 500px and we apply a value of 0.5, we get a new width of 250px. The “skew” effect accepts degree values for how much the element should be skewed along the X and Y axises. Both the scale and skew, similar to the translate effect, have an X and Y only effect as well, which are scaleX(<value>), scaleY(<value>), skewX(<degrees>), skewY(<degrees>).