CSS3 transform rotate without overriding transform translate

5.2k Views Asked by At

Let's say I have an element that already has a translate applied to it:

<div class="elem"></div>

.elem { transform: translate(50%,0); }

And now I want to rotate the same element using an additional class. So now the HTML and CSS looks like this:

<div class="elem rotate"></div>

.elem { transform: translate(50%,0); }
.rotate { transform: rotateZ(20deg); }

The problem occurs when the rotation is not added to the existing translate, but rather overrides and negates it.

How do I preserve the original translate without having to bloat up my code like I did below:

.elem { transform: translate(50%,0); }
.rotate { transform: translate(50%,0) rotateZ(20deg); }

Here's a fiddle: https://jsfiddle.net/timothyzhu/vm84vsj7/

Thanks guys.

1

There are 1 best solutions below

3
On

Setting a transform property on an element will override any other transform property set previously on the same element.

One common pattern in this situation is use JS to store the value and then apply transformation taking into account the previous transform property(also because the sequence of transformations is important!!).

In your scenario, a workaround could be creating a wrapping div just for rotation (here's a complicated example look at it with dev-tools),

fiddle