Set CSS transform in multiple places

Viewed 1243

Is there any way to set style transform: translateX(100px) translateY(200px) rotate(100deg) scale(1.5) on multiple places? For example, there are these lines in CSS:

.translate-x {
    transform: translateX(100px);
}

.translate-y {
    transform: translateY(200px);
}

.rotate {
    transform: rotate(100deg)
}

.big {
    transform: scale(1.5);
}

And then, I would like use these classes in HTML to combine transform.

<div class="translate-x rotate big"></div>
<div class="translate-y big"></div>
...

The problem is that the styles do not combine, but the last one will overwrite the others.

Only way what I know is combine all classes. But there are many combinations...

.translate-x.translate-y {
    transform: translateX(100px) translateY(200px);
}

.translate-x.translate.y.big {
    transform: translateX(100px) translateY(200px) scale(1.5);
}

...
2 Answers

As the answer stated above said this currently is impossible by means of lone css. You'd need to use javascript to apply it for you.

Here is a small jQuery example

$('.my-element').css({
'transform': 'translateX(100px) translateY(200px) rotate(100deg) scale(1.5)'
});

The vanilla JS way is the following:

var myElement = document.getElementsByClassName('my-element');
myElement.style.transform = 'translateX(100px) translateY(200px) rotate(100deg) scale(1.5)';

You should be able to use the following 3 methods to apply either:

  1. Event listeners (preferably with event delegation)
  2. Functions
  3. Just including your script at the bottom of the body so that the elements render before they are transformed to prevent glitching.
Related