abs()
Baseline 2025Newly available
Since June 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Theabs()CSSfunction returns the absolute value of the argument, as the same type as the input.
In this article
Syntax
/* abs( <calc-sum> ) */abs(20% - 100px)abs(var(--gradientAngle))Parameters
Theabs() function accepts one parameter.
<calc-sum>An expression or calculation that resolves to a
<number>, a<dimension>, a<percentage>or a<calc-keyword>.
Return value
The absolute value of<calc-sum>.
- If
<calc-sum>'s numeric value is positive or0⁺, the function returns<calc-sum>. - Otherwise, it returns
-1 * <calc-sum>.
Formal syntax
<abs()> =
abs(<calc-sum>)
<calc-sum> =
<calc-product>[[ '+'| '-']<calc-product>]*
<calc-product> =
<calc-value>[[ '*'| /]<calc-value>]*
<calc-value> =
<number>|
<dimension>|
<percentage>|
<calc-keyword>|
(<calc-sum>)
<calc-keyword> =
e|
pi|
infinity|
-infinity|
NaN
Examples
>Positive variables
Theabs() function can be used to ensure that a value is always positive. In the following example a CSS custom property--font-size is used as the value offont-size. Wrapping this custom property inabs() will convert a negative value to a positive one.
h1 { font-size: abs(var(--font-size));}Control gradient angle of direction
You can also control the gradient direction usingabs() function. In the following example, with an angle of -45deg the gradient would start red and transition to blue. By usingabs() to make the value positive, the gradient will start blue and transition to red.
div { --deg: -45deg; background-image: linear-gradient(abs(var(--deg)), blue, red);}Backwards compatible fallback
In browsers that lack support for CSSabs() function, you can use the CSSmax() function to achieve the same result:
p { line-height: max(var(--lh), -1 * var(--lh));}We use themax() function to return the largest (most positive) value from a list of two values:var(--lh) or-1 * var(--lh). Irrespective of whether--lh is positive or negative, the calculated return value will always be positive, that is, an absolute number.
Specifications
| Specification |
|---|
| CSS Values and Units Module Level 4> # sign-funcs> |