Search code examples
csscss-transformscss-calc

Why does this calc() function not work in transform scale?


calc() apparently works in a transform, but this does not:

transform: scale(calc(0.75 + (0.3 - 0.75) * ((100vw - 320px) / (780 - 320))));

Also, this works, but it's basically the same formula, only with a percent vs decimal. Only added this so you can see the formula works here:

right: calc(30% + (75 - 30) * ((100vw - 320px) / (780 - 320)));

I have a container that has a width as a percent, and max width of 300px, for example. I want a child of it to always scale, using transform:scale(), to a percent of the parent's actual current width.

Why does my transform calc function not work? Using Chrome.

The 100vw - 320px is there to calculate between minimum an max size of the window width. Is it possible to do that here?


Solution

  • It turns out that it's possible by using a very smart hack as explained in https://dev.to/janeori/css-type-casting-to-numeric-tanatan2-scalars-582j and futher developed in https://css-tricks.com/typecasting-and-viewport-transitions-in-css-with-tanatan2/

    @property --100vw {
      syntax: "<length>";
      initial-value: 0px;
      inherits: false;
    }
    
    :root {
      --100vw: 100vw;
      --int-width: calc(10000 * tan(atan2(var(--100vw), 10000px)));
    }
    

    and then use it this way

    transform: scale(calc(0.75 + (0.3 - 0.75) * ((var(--int-width) - 320) / (780 - 320))));