Individual CSS Transform Functions

Avatar of Chris Coyier
Chris Coyier on

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

Dan Wilson documents a classic annoyance with transforms:

button {
  transform: translateY(-150%);
}
button:hover {
  /* will (perhaps unintentionally) override the original translate */
  transform: scale(.8);
}

The native (and WET) solution is list the original transform again:

button:hover {
  transform: translateY(-150%) scale(.8);
}

Dan’s trick is to use custom properties instead. Set them all on the element right up front, then re-set them the :hover state:

:root {
  --tx: 150%;
  --scale: 1;
}
button {
  transform: 
    translateY(var(--tx))
    scale(var(--scale));
}
button:hover {
  --scale: 0.8;
}

Cascading custom properties FTW.

Direct Link →