cssmathcalccss-calc

How to use a "reverse percentage"/unitless calculation in a CSS calc()?


I would like to use the following calculation in the width and height of an element:

(1 / 0.65) * 100, then the % sign

So that the width & height are set to 153.85%.

However I believe the first number must have units, or be a percentage - in order for calc to work.

How can I set this in calc rather than hardcoding it to 153.85%?

153.85% being the reverse percentage of 65% - per this Math.SE question.

I tried calc(100% / 65%) but this was marked as invalid syntax.


Solution

  • You can convert the percentage into "raw" form, and then do your calculation:

    calc((100% * 100) / 65);
    

    (100% * 100) / 65 behaves consistently and correctly in css because it correctly manipulates units according to css rules. (100% / 0.65) uses direct division of a percentage by a unitless number and might not be supported by different browsers consistently. Also using the method shown above maintains the percentage throughout the calculation, whereas the latter does not.