CSS Transforms

By

Tagged: CSS

Learn how the CSS transform property lets you translate, rotate, scale, and skew elements in 2D and 3D space, and combine transforms with perspective.

Transforms allow you to translate, rotate, scale, and skew elements, in the 2D or 3D space. They are a very cool CSS feature, especially when combined with animations.

2D transforms

The transform property accepts those functions:

We also have axis-specific functions:

Here is an example of a transform which changes the .box element width by 2 (duplicating it) and the height by 0.5 (reducing it to half):

.box {
	transform: scale(2, 0.5);
}

You can also set translate, rotate and scale as their own properties (Chrome 104, Firefox 72, Safari 14.1; Baseline since 2022):

.box {
  translate: 10px 20px;
  rotate: 45deg;
  scale: 1.5;
}

They apply in a fixed order: translate, then rotate, then scale, then transform. You can animate each one separately. That pairs well with CSS animations and CSS transitions.

transform-origin lets us set the origin (the (0, 0) coordinates) for the transformation, letting us change the rotation center.

Combining multiple transforms

You can combine multiple transforms by separating each function with a space.

For example:

transform: rotateY(20deg) scaleX(3) translateY(100px);

3D transforms

We can go one step further and move our elements in a 3D space instead than on a 2D space. With 3D, we are adding another axis, Z, which adds depth to our visuals.

Using the perspective property you can specify how far the 3D object is from the viewer. Put perspective on the parent. It applies to that parent’s 3D-transformed children. The perspective() function inside transform applies to the element itself.

Example:

.element-3d {
  perspective: 100px;
}

perspective-origin determines the appearance of the position of the viewer, how are we looking at it in the X and Y axis.

Now we can use additional functions that control the Z axis, that adds up to the other X and Y axis transforms:

translate3d() and scale3d() are the shorthands for the X/Y/Z functions. rotate3d() is not a shorthand for rotateX() / rotateY() / rotateZ(). It rotates around an arbitrary [x, y, z] axis vector: rotate3d(x, y, z, angle).

Want me to talk about your product? You can sponsor this site.

Related posts about css: