Home > Mobile >  How to chain parent and child css transform vars
How to chain parent and child css transform vars

Time:05-20

In the example below only the first Hello gets sized down to 0.8. The second one keeps its original scale(1,-1) ignoring the parent transform.

I want the parents transforms to be chained.

I know I can apply the transform directly on the div and it would affect both children at the same time but I want each children to be transformed independently not together that's why I'm using css vars here (it's subtle but there is a difference) check here to see it

I need some way to do this keeping only one css var (cause I'll have multiple nested divs with different consecutive transforms applied on the inner paragraphs).

Please any idea is really appreciated, will be using js if really needed.

p { transform: var(--transf); }
<div style="--transf: scale(0.8)">
      <div><p>Hello</p></div>
      <div style="--transf: scale(1,-1);"><p>Hello</p></div>
</div>

CodePudding user response:

Maybe this can work for you.

I can't seem to find a way to "chain" strings of transform functions.

But you can set a base of default values and apply many transforms to p elements and set the appropriate values at each level which may give you a chain effect due to the cascade.

/* You can extend this for as many properties as you need*/
div.base {
  --scaleX : 1;
  --scaleY : 1;
  --rotate : 0deg;
  --translateX : 0px;
  --translateY : 0px;
}

div div {
  width: 200px;
}

/* Likewise you can extend the transform function as you need*/
p {
  border: 1px dashed gray;
  transform: scale(var(--scaleX), var(--scaleY))
             rotate(var(--rotate)) 
             translate(var(--translateX), var(--translateY));
}
<div >
  <div style="--scaleX:.8; --rotate:45deg; --translateX:80px;">
    <p>Hello 1</p>
  </div>
  <div style="--scaleY:-1;">
    <p>Hello 2</p>
  </div>
  <div style="--scaleX: .5; --scaleY:.5; --rotate:60deg;">
    <p>Hello 3</p>
  </div>
</div>

  • Related