abs()

The abs() CSS function contains one calculation, and returns the absolute value of the argument, as the same type as the input.

The abs(A) statement will return A if A’s numeric value is positive or 0⁺. Otherwise it will return the value of -1 * A.

Syntax

/* property: abs(expression) */
width: abs(20% - 100px);

The abs() function takes only one expression as its argument.

Formal syntax

{{CSSSyntax}}

Examples

Positive variables

The abs() 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 of font-size. Wrapping this custom property in abs() 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 using abs() function. In the following example, with an angle of -45deg the gradient would start red and transition to blue. By using abs() 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);
}

Specifications

Specification Status Comment
CSS Values and Units Module Level 4
The definition of 'abs()' in that specification.
Editor's Draft Initial definition

Browser compatibility

No compatibility data found for css.types.abs.
Check for problems with this page or contribute missing data to mdn/browser-compat-data.

See also