Transforms

CSS · Practical · 8 min

Transforms power hover effects, icons, carousels and smooth animations without disturbing the layout.

Transforms change how an element is drawn without changing layout: its original box still occupies the same space, and neighbours don't move.

The functions:

  • translate(x, y) moves it; percentages are relative to the element's own size, so translate(-50%, -50%) shifts by half its own width and height.
  • rotate(45deg) (or 0.25turn), scale(1.1) or scale(x, y), skew(10deg).
  • 3D: rotateY(), translateZ(), perspective().

In the transform property, functions apply right to left in terms of coordinate space, so order matters: rotate(45deg) translateX(100px) moves along the rotated axis, while translateX(100px) rotate(45deg) moves right and then rotates in place.

Modern CSS also has the individual properties translate, rotate and scale. They're applied in a fixed order (translate, rotate, scale, then transform), and you can change one without repeating the others, which is ideal for transitions and hover states.

transform-origin sets the pivot point; the default is the center. transform-origin: top left makes a menu scale out from its corner.

Side effects to know: a transform creates a new stacking context and becomes the containing block for position: fixed descendants, so a fixed element inside a transformed parent stops being fixed to the viewport.

Example

.card { transition: scale 200ms ease, rotate 200ms ease; }
.card:hover { scale: 1.03; }

.icon-chevron { rotate: 0deg; transition: rotate 150ms; }
details[open] .icon-chevron { rotate: 90deg; }

.menu {
  transform-origin: top right;     /* grow from the corner */
  scale: 0.95;
  opacity: 0;
}
.menu.open { scale: 1; opacity: 1; }

/* order matters in the transform function list */
.a { transform: rotate(45deg) translateX(100px); }  /* moves diagonally */
.b { transform: translateX(100px) rotate(45deg); }  /* moves right, then spins */

Remember

  • Transforms don't affect layout; neighbours stay put
  • Function order in transform matters
  • translate, rotate and scale properties can be changed independently
  • A transform creates a stacking context and traps fixed descendants

Watch out for

  • Putting a position: fixed modal inside a transformed parent and seeing it scroll with the page.

Check yourself

  1. A box is translated 50px to the right with transform. What happens to the element after it?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/transform