CSS atan2() Function
The atan2() function is a CSS math function that calculates the angle of a specific point relative to the positive X-axis.
While the standard atan() function takes a single ratio to find an angle, atan2() takes two separate arguments representing the Y and X coordinates (in that specific order). By looking at both coordinates, the browser can determine exactly which quadrant of the circle the point is in, returning a precise angle between -180deg and 180deg.
Another major advantage of atan2() is that it accepts dimensions (like pixels, rems, or percentages), as long as both arguments share the same unit type. This makes it quite practical for calculating angles based on actual layout dimensions.
For example:
atan2(1, 1)returns45degatan2(1, -1)returns135degatan2(-100px, 0px)returns-90deg
This function is a great tool when you need to orient an element to face a specific coordinate on the screen. Here is a basic example where we pass two CSS custom properties (representing Y and X) into the atan2() function to rotate a box:
How It Works
The atan2() function requires two comma-separated calculations. The first argument represents the Y-axis (vertical) value, and the second represents the X-axis (horizontal) value.
Similar to the calc() function, atan2() resolves mathematical expressions on the fly. You can write equations directly inside the function, such as atan2(var(--y) * 2, var(--x) + 50px).
Official Syntax
The official syntax of the atan2() function is as follows:
Possible Values
As indicated in the official syntax, the atan2() function accepts two values:
- calc-sum
Two mathematical calculations representing the Y and X coordinates, respectively. These can be unitless numbers, lengths, or percentages, but both arguments must resolve to the same type (e.g., you cannot mix a length with a unitless number).
CSS Specifications
- The
atan2()function is defined in CSS Values and Units Module Level 4 (Editor's Draft)
Browser Support
The following table provided by Caniuse.com shows the level of browser support for this feature.