CSS abs() Function
The abs() function is a CSS math function that returns the absolute value of a calculation.
In mathematics, an "absolute value" is simply the distance of a number from zero, regardless of its direction. In practical terms, this means the abs() function always returns a positive number. If you give it a positive value, it stays positive. If you give it a negative value, it drops the minus sign and becomes positive.
This can be useful when you're working with CSS custom properties (variables) or complex calc() equations. Sometimes, a dynamic calculation might result in a negative number. While some CSS properties (like margin or translate) accept negative values, others (like width, height, or padding) strictly require positive values and will break if fed a negative number.
By wrapping your variable or calculation in abs(), you guarantee that the resulting value is always safe to use for properties that require positive dimensions. Here's an example where we have a CSS variable set to a negative value (-150px). We use it directly to move a box to the left, but we use abs() to safely apply that same value to the box's width:
How It Works
The abs() function takes a single calculation as its argument. This can be a straightforward value (like abs(-50px)), a CSS variable (like abs(var(--my-val))), or a full mathematical equation (like abs(10vw - 500px)).
It's also worth noting that abs() automatically performs calculations just like the calc() function does. You don't need to nest a calc() inside an abs(); you can just write the math directly inside the parentheses.
Official Syntax
The official syntax of the abs() function is as follows:
Possible Values
As indicated in the official syntax, the abs() function accepts the following value:
- calc-sum
A mathematical calculation that resolves to a number, dimension (like a length or angle), or percentage. The function will evaluate this calculation and return its absolute (positive) value.
CSS Specifications
- The
abs()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.