abs()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

abs() CSS 関数 は、引数の絶対値を同じ型で返します。

構文

css
/* プロパティ: abs(式) */
width: abs(20% - 100px);

引数

abs(x) 関数は、1つの引数を受け取ります。

x

数値に解決される計算式です。

返値

x の絶対値を返します。

  • もし x の数値が正または 0⁺ であれば、x を返します。
  • そうでない場合は、-1 * x を返します。

形式文法

<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

正の変数

abs() 関数を使用すると、値が常に正となることを保証できます。次の例では、--font-size という CSS カスタムプロパティが font-size の値として使用されています。このカスタムプロパティを abs() で囲むと、負の値が正に変換されます。

css
h1 {
  font-size: abs(var(--font-size));
}

グラデーション方向の角度を制御する

abs() 関数を使用して、グラデーションの方向を制御することもできます。次の例では、角度が -45 度の場合、グラデーションは赤から青に変化します。abs() を使用して正の値にすると、グラデーションの変化は青から赤になります。

css
div {
  --deg: -45deg;
  background-image: linear-gradient(abs(var(--deg)), blue, red);
}

後方互換性のためのフォールバック

CSS abs() 関数をサポートしていない古いブラウザでは、次のように CSS max() 関数を使用することで同じ結果を得られます。

css
p {
  line-height: max(var(--lh), -1 * var(--lh));
}

max() 関数により、var(--lh)-1 * var(--lh) のうち大きい値が返されます。--lh が正であれ負であれ、返される値は常に正であり、これは絶対値となります。

仕様書

Specification
CSS Values and Units Module Level 4
# sign-funcs

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
abs()

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.

関連情報