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

  • You have two issues. The first one is about the formula without scale:

    calc(0.75 + (0.3 - 0.75) * ((100vw - 320px) / (780 - 320)))
    

    This is invalid because you are adding a number (0.75) with a length ((0.3 - 0.75) * ((100vw - 320px) / (780 - 320)))

    At + or -, check that both sides have the same type, or that one side is a <number> and the other is an <integer>. If both sides are the same type, resolve to that type. If one side is a <number> and the other is an <integer>, resolve to .ref

    The second issue, is that scale only take a number so you need to correct the formula to transform the second part into a number by removing any kind of unit (vw,px,etc).

    Basically, what you want to do cannot be done this way because you have no way to convert your (100vw - 320px) to a number unless you consider using some JS as this is beyond CSS. Even with JS you will need to define what is the logic behind transforming a pixel number to non-pixel number.


    Using the same formula within right and with percentage will work fine because:

    If percentages are accepted in the context in which the expression is placed, and they are defined to be relative to another type besides <number>, a <percentage-token> is treated as that type. For example, in the width property, percentages have the <length> type. A percentage only has the <percentage> type if in that context <percentage> values are not used-value compatible with any other type. If percentages are not normally allowed in place of the calc(), then a calc() expression containing percentages is invalid in that context.ref

    So in this case percentage is allowed to be used with right because we can resolve it thus the forumla will be valid because at the end it will be something like A% + Bpx.