Mocking Individual CSS Transform Functions using CSS Variables

In CSS we use the transform property to manage an element’s translation, rotation, and scale. As it’s one single combined property for all three possible transformations, setting transform: rotation(90deg); on an element will (re)set the values for translation and scale by falling back to their default values.

This will change when the “CSS Transform Module Level 2” spec will be approved and implemented (currently already partly in Chrome Canary), as it introduces separate properties for each possible transformation:

The translate, rotate, and scale properties allow authors to specify simple transforms independently, in a way that maps to typical user interface usage, rather than having to remember the order in transform that keeps the actions of translate(), rotate() and scale() independent and acting in screen coordinates.

Dan Wilson created a nice demo to already use this kind of behavior today, with the help of CSS Variables. Initially the CSS transform is set to the default values using this snippet:

:root {
  --tx: 0;
  --ty: 0;
  --scale: 1;
  --deg: 0deg;
}

el {
  transform: 
    translate3d(calc(var(--tx) * 1vw), calc(var(--ty) * 1vh), 0) 
    scale(var(--scale)) 
    rotate(var(--deg));
}

As the transformation property values are linked to the CSS variables you can now change them individually – be it in CSS or via JS – just like the “CSS Transform Module Level 2” allows one to do.

Not entirely familiar with CSS Variables? CSS Variables: var(–subtitle); is a good video/presentation to get you started.

Here’s a demo that uses JS to change the individual values:

A Trick: Individual CSS Transform Functions →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.