CSS変数について

CSS変数(カスケード変数/カスタムプロパティ)とは、Sassなどのプリプロセッサを利用せずとも、設定値を変数で一括管理できる機能である

対応状況

本記事の執筆時点では、ほとんどのブラウザが対応している

参考:”Custom Properties” | Can I use… Support tables for HTML5, CSS3, etc https://caniuse.com/?search=Custom Properties

利用例

次のように、cssのvar関数を利用して値をセットし、スタイリングできる

:root {
	--primary-color: blue;
}

elm.class {
	color: var(--primary-color);
}

スコープについて

変数のスコープは要素内である。また、値が存在しない場合にはフォールバック設定をすることができる。例えば次の通り。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* global scope */
    :root { 
      --primary-color: blue;
    }

    /* local scope */
    .reddener {
      --primary-color: red;
    }

    p { 
      color: var(--primary-color);

      /* フォールバックする */
      font-size: var(--nothere, 30px);
    }

  </style>
</head>
<body>
  <div class="container">
    <p>texttexttext</p>
    <div class="reddener">
      <p>texttexttext</p>
    </div>
  </div>
</body>
</html>

動的な処理について

calcを組み合わせて利用することも可能

:root{
	--size: 30;
}

elm.class {
	font-size: calc(var(--size) * 1px);
}

JSによる操作も可能。ちなみに、Sassではこのような操作はできない。

/* css */
:root{
	--size: 30;
}

elm.class {
	font-size: calc(var(--size) * 1px);
}

// js
const selector = getComputedStyle(document.querySelector('elm.class'));
const result = selector.getPropertyValue('--color');

console.log(result); // show "blue"

おわりに

変数を利用するという点では、SassよりもCSS変数を利用したほうが取り回しやすいと思う。

投稿者: hirobel

JavaScriptが好きです

コメントをどうぞ

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

PAGE TOP
Close Bitnami banner
Bitnami