Transforms

CSS Transforms give you the power to change the shape, size, and position of elements without affecting the normal document flow. Unlike changing top or left properties, transforms are highly efficient because they are often hardware-accelerated by your computer's GPU.

Whether you want to slant a button, flip a card, or zoom into an image, the transform property is your go-to tool.

1. 2D Transformations

2D transforms operate on the X (horizontal) and Y (vertical) axes. There are four primary functions you will use:

  • translate(x, y): Moves the element from its current position.
  • rotate(angle): Spins the element (e.g., 45deg).
  • scale(x, y): Changes the size (e.g., 2 doubles the size, 0.5 halves it).
  • skew(x-angle, y-angle): Slants or twists the element along the axes.

Interactive 2D Transform Demo

Code Block Loading...

2. The transform-origin Property

By default, every transformation happens from the center (50%, 50%). The transform-origin property allows you to change the pivot point. For example, setting it to top left makes an element rotate around its corner like a swinging door.

Code Block Loading...

3. Combining Multiple Transforms

You don't have to choose just one! You can chain transforms by separating them with spaces. Note that the order matters—rotating and then translating gives a different result than translating and then rotating.

Code Block Loading...

4. Introduction to 3D Transforms

3D transforms introduce the Z-axis, which represents depth (moving toward or away from the viewer). To make 3D effects visible, you must use the perspective property on the parent container. This determines how "far" the viewer is from the object.

  • translateZ(): Moves an object closer or further away.
  • rotateY(): Spins an object like a revolving door.
  • rotateX(): Spins an object like a wheel.

Interactive 3D Rotation Demo

Code Block Loading...

Key Takeaways

  • Non-Disruptive: Transforms do not push other elements around. An element moved with translate still occupies its original space in the layout.
  • Efficiency: Use transforms instead of top/left or width/height for animations to ensure smooth 60fps performance.
  • Order Matters: transform: rotate(45deg) translate(50px) is not the same as translate(50px) rotate(45deg).
  • 3D Requires Perspective: Without the perspective property on a parent, 3D rotations will look flat and 2D.
  • The Origin: Use transform-origin to change the anchor point of your animations (e.g., making a clock hand rotate from the bottom).