stack css transforms

Apr 4, 2020
3 minutes to read

This is something simple but it blew my mind when I discovered it. You can stack CSS transforms for the same direction and all of them get applied 🤯

transform: translateY(-100%) translateY(40px);

Let me illustrate this with a use-case. Let’s say you have a drawer component that slides in and out of view

<button @click=“showFirst = !showFirst”>toggle #1

Peek-a-boo 👀

We would achieve this by moving the container fully off screen with transform: translateX(100%) and then when a certain condition is filled, navigate it back with transform: translateX(0).

But what if we want to keep a certain part of the element visible in one state? With our current approach, we could fine-tune the initial transform value and end up with something like
transform: translateY(75%) 👇

<button @click=“showSecond = !showSecond”>toggle #2

Meow
...is what a cat says!

Again, this works for this example.. But as soon as the content’s height changes, the absolute value of the translateY(75%), that works for our current example, will throw us off..

<button @click=“showThird = !showThird”>toggle #3

Meow
...is what a cat says! A cat is a feline. Imagine more text here, which makes the container taller and hence results in a bigger value for the 75% that we're transforming.

This is where the stackable transform declarations come in! Let’s rework our example with transform: translateY(100%) translateY(-50px);. This example is editable! Toggle it, add some newlines or silly text and toggle it some more. See that no matter the container height, it will always display just the 50px part from the top.

<button @click=“showFourth = !showFourth”>toggle #4

Meow
...is what a cat says! Go ahead and edit this text to try out different heights.