cssmodularity

css transform specified by class


I am looking for a way in vanilla css or css preprocessor such that

When class1 and class2 both have a transform property defined, a single html element of class1 and class2 has both transformations applied.

That is to say, I am looking for a way such that a class is only controlling one set of transformations. Right now it appears the last class defined in the css file has its transformation(s) displayed. I am not familiar with css preprocessors so if one of them has this feature please also link to a post/article/reply that summarizes what the preprocessor could do in general.

I am aware of methods of introducing wrapper html elements, one for each set of transformations, and using += in js. But I'm specifically looking for a css solution. I am open to altering html if it's just going to be a fixed number of elements regardless of the number of transformations.

.scale {
  transform: scale(0.8) rotate(4deg);
}

.translate {
  transform: translate(20px);
}

div {
  border: 2px solid black;
}
<div>text</div>
<div class="scale">text</div>
<div class="translate">text</div>
<div class="scale translate">text</div>
<div class="translate scale">text</div>

I know that order matters in transformations. But I am not concerned about that at the moment. I just want to know if there there exists a way to modify instead of overwrite a rule.


Solution

  • You can do that using CSS custom properties (variables):

    * {
        /* space before semicolon is essential
           to make it a valid empty value */
        --scale: ;
        --translate: ;
    }
    
    .scale {
        --scale: scale(0.8) rotate(4deg);
    }
    
    .translate {
        --translate: translate(20px);
    }
    
    .scale,
    .translate {
        transform: var(--scale) var(--translate);
    }