LoginSignup
34
26

More than 3 years have passed since last update.

CSSでも変数定義できるんだよっ!

Last updated at Posted at 2019-07-17

実は結構前からあったみたいですが、最近知りました。

その名は カスタムプロパティ

 カスタムプロパティ
 https://developer.mozilla.org/ja/docs/Web/CSS/Using_CSS_custom_properties
 #IEは例によってサポート外です・・・

Qiitaにも過去に紹介あったようです。

 CSS Variables(カスタムプロパティ)でCSSがより便利に!
 https://qiita.com/kyota/items/bd5d291809415cc2d7b1

何が嬉しいのか

Sass/LESSで出来てた変数定義がCSS単体でもできます。

・・・だけだと、Sass/LESSの方がもっと機能がたくさんあるから良いじゃんという結論になりますが、個人的には動的に変更可能なところが嬉しいと思ってます。

具体例

よく、WEBサイトで文字サイズの大中小が切り替えれたり、テーマが切り替えれたりできますよね。
あれがカスタムプロパティでも実現できそうです。

zoomという機能もありますが、Firefoxでは動かないようだし、標準的な機能でもありません。

 zoom
 https://developer.mozilla.org/ja/docs/Web/CSS/zoom

ということで実際に作ってみたデモはこちらです。

mov.gif

 デモサイト
 http://megyo.jp/software/samples/css-var-sample/index.html

 デモサイトのソース(GitHub)
 https://github.com/uemegu/Sampes/tree/master/css-var-sample

デモの中では2パターンのやり方で変数を書き換えてます。

// 変数だけを定義したCSSを読み込み直す
document.getElementById("button").onclick = () => {
    const link = document.querySelector('link[rel="stylesheet"]');
    link.href = link.href.includes('variables1.css') ? 'variables2.css' : 'variables1.css';
};

// JavaScriptでカスタムプロパティを書き換える
document.getElementById('button2').onclick = () => {
    const color = document.documentElement.style.getPropertyValue('--background');
    document.documentElement.style.setProperty('--background', color === 'black' ? 'white' : 'black');
};

また、試したみたらSassと組み合わせて利用することもできました(LESSは確認してません)。

:root {
  --font-size: 18px
}
$font_size_normal: var(--font-size);

まとめ

実際の業務ではまだ使ったことはないのですが、IEを考えなくて良い場合は使えるシーンが多いのではないでしょうか。

IEがこの世からなくなることが働き方改革じゃないかと、今日思いました。

34
26
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
26