LoginSignup
1
0

More than 1 year has passed since last update.

CSS変数を使ってみる

Last updated at Posted at 2022-12-08

ひとりCSS Advent Calendar 2022 9日目です。

CSS変数を使ってみます。

変数

Sass(SCSS) での書き方

変数の頭に $ マークをつける

$text-color: #333;

p {
  color: $text-color;
}

CSS での書き方

  • 基本はルート擬似クラス :root {...} の中に書く。
    • ルートでなくても一般的なにセレクタの中でも設定できる
    • スコープを絞るとか?
  • 変数の頭に -- をつける。

使うときは var() で囲む。

:root {
  --text-color: #333;
}

p {
  color: var(--text-color);
}
  • 大文字小文字を区別するらしい
    • --color と --Color は別物

JS で使える

  • getPropertyValue
  • setProperty

遊んでみる

image.png

:root {
  --christmas-color1: red;
  --christmas-color2: green;
}

div {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

p {
  font-size: 10vw;
  font-weight: 600;
  font-family: Avenir, sans-sarif;
}

.christmas {
  color: var(--christmas-color1);
  background: repeating-linear-gradient(
    -45deg,
    var(--christmas-color1),
    var(--christmas-color1) 10px,
    var(--christmas-color2) 10px,
    var(--christmas-color2) 20px
  );
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-fill-color: transparent;
}

感想

  • Sassと比べるとやや記述量が多いが便利

参考

1
0
0

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
0