Vesmy
Vesmy

Reputation: 1278

Set CSS transform in multiple places

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);
}

...

Upvotes: 4

Views: 1666

Answers (2)

Callat
Callat

Reputation: 3044

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.

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157334

Unfortunately, you cannot do it. Syntax for transform is as follows,

transform: none|transform-functions|initial|inherit;

So when you call multiple classes on your HTML element, only the last class declared in your CSS is applied. (class order doesn't matter in HTML)

The best you can do is use CSS preprocessor with a function which will generate a string of these transform functions called in one declaration so that they don't override.

Upvotes: 3

Related Questions