csssvgcss-animations

Is there a way to have pi in a CSS calc?


I have an SVG circle animation for a progress bar where the stroke-dashoffset is animated from 0,radius to radius,0 (for 0% to 100%).

The equation for the length of the circumference of a circle is pi * d. Is there a way to use a CSS calc function where it can use a value of pi, rather than just a rounded value (like 3.14)?


Solution

  • There is now a <calc-constant> pi constant that can only be used in CSS calc() math functions:

    .circle {
      --diameter: 3px;
      --circumference: calc(pi * var(--diameter));  /* <-- `pi` */
      stroke-dashoffset: var(--circumference);
    }
    

    However, the browser support is bad. (As of August 2023, it's only Safari and Firefox.)

    Actually, November 2023 update, the support is currently quite alright! (90%+ globally)


    Instead, you can use CSS variables to assign a number to it:

    :root {
      --pi: 3.14159265358979;
    }
    
    .circle {
      --diameter: 3px;
      --circumference: calc(var(--pi) * var(--diameter));
      stroke-dashoffset: var(--circumference);
    }
    

    As mentioned in the comments, some browsers (Safari + IE) round to 2 decimals, where Chrome and Firefox can round up to (at least) 4 decimals.


    Another solution would be to use a preprocessor such as SASS or Less to assign the PI variable to.

    For example, using SASS:

    $pi: 3.14159265358979
    
    .circle {
      --diameter: 3px;
      --circumference: calc(${pi} * var(--diameter));
      stroke-dashoffset: var(--circumference);
    }