Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 369
Philip Eagles Avatar asked Nov 24 '16 09:11

Philip Eagles


People also ask

How do you calculate pi in HTML?

To get the value of PI in JavaScript, use the Math. PI property. It returns the ratio of the circumference of a circle to its diameter, which is approximately 3.14159.

Can you do math in CSS?

calc() is a native CSS way to do simple math right in CSS as a replacement for any length value (or pretty much any number value). It has four simple math operators: add (+), subtract (-), multiply (*), and divide (/).


1 Answers

There's no such thing as a PI variable in CSS, unfortunately.

However..

You can make use of CSS variables to assign a number to it, downside to this is that it has a really, really bad browser support. Well, not any more

This would work like:

:root {   --PI: 3.14159265358979; // enter the amount of digits you wish to use }  .circle {     width: calc(100 * var(--PI)); } 

The best solution would be to use a preprocessor such as SASS or Less to assign the PI variable to, this would look like the following example in SASS:

$pi: 3.14159265358979 // amount of digits you wish to use  .circle {     width: calc(100 * ${pi}); } 

EDIT: 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.

like image 160
roberrrt-s Avatar answered Sep 29 '22 02:09

roberrrt-s