1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSS変数とは、変数を使って、色やサイズなどの値をまとめて管理できる機能です。

定義

CSS変数の宣言

:root {
  --my-color: blue;
}
  • :rootは HTML全体に適用される特別な擬似区タス(グローバル変数みたいな感じ)
  • 最初に--とつける
  • 大文字と小文字が区別される

CSS変数を使う

h1 {
  color: var(--My-color, orange);
  border-bottom: 3px solid var(--my-color);
}
  • var(--変数名)で変数を読み込んで使う
  • ,XXで宣言されていない場合の初期値を設定できる

注意点

  • CSS 変数はプロパティの値に使えるのであって、プロパティ名のほうには使うことはできません。
プロパティ名: プロパティ値
  • あとから単位を追加することができない
:root {
 --my-margin-left: 32;
}

上記のようにCSS変数を宣言し、単位を追加してもうまくいかない。

h1 {
  margin-left: var(--my-margin-left)px;
}

解決方法1:宣言時に単位を設定しよう!

:root {
  --my-margin-left: 32px;
}

解決方法2:calc関数を使用しよう!

:root {
  --my-margin-left: 32;
}

h1 {
  margin-left: calc(var(--my-margin-left) * 1px);
}

テーマカラーの設定

  • 200に設定
:root {
  --my-hue: 200;
}
  • 変数を使うだけ!
body {
  background: hsl(var(--my-hue), 40%, 95%);
}
  • 真反対の補色も簡単
 background: hsl(calc(var(--my-hue) + 180), 50%, 50%);
1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?