Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The abs()
CSS function returns the absolute value of the argument, as the same type as the input.
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The abs()
CSS function returns the absolute value of the argument, as the same type as the input.
/* property: abs(expression) */ width: abs(20% - 100px);
The abs(x)
function accepts only one value as its parameter.
x
A calculation which resolves to a number.
The absolute value of x
.
x
's numeric value is positive or 0⁺
, return x
.-1 * x
.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)); }
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); }
In older browsers that lack the support for CSS abs()
function, you can use the CSS max()
function to achieve the same result, as shown below:
p { line-height: max(var(--lh), -1 * var(--lh)); }
We use the max()
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.
Specification |
---|
CSS Values and Units Module Level 4 # sign-funcs |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
abs |
No | No | No | No | No | 15.4 | No | No | No | No | 15.4 | No |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/abs