2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sass と CSS変数 を組み合わせて色をラクラク管理する

Last updated at Posted at 2022-03-23

今まで Sass と CSS変数 を組み合わせた利用はできないと思っていました。

がしかし:exclamation::exclamation:

インターポレーション #{} を利用すれば利用できたんですね…:sweat_drops:
もっと早く知りたかった…:sweat:

たとえば、カテゴリーごとに見出しやボタンなど、要素の色を変えることって結構ありますよね?

今までは Sass のマップで色を管理し、 @each を使って各セレクタに色を設定していました。
これだと、色を変更する要素が増える度に設定しなければならず、とっても大変…

というわけで、Sass と CSS変数 を組み合わせて色をラクラク管理しちゃいます!

準備

Sass のマップを利用して色を管理します。
そして、 @each を使って body 要素にカテゴリーごとのCSS変数を設定します。

scss
$category-colors: (
  'primary': #FF0000,
  'secondary': #0000ff,
  'tertiary': #ffff00
);

@each $name, $color in $category-colors {
  body.#{$name} {
    // インターポレーションを利用してCSS変数にSass変数を代入
    --category-color: #{$color};
  }
}

色を利用する

CSS

色を利用したい要素にCSS変数を設定します。

style.css
.title {
  color: var(--category-color);
}
.btn {
  background-color: var(--category-color);
}

HTML

利用したい色のカテゴリー名(Sass のマップのキー)を body 要素の class に設定します。

body 要素の class名 を変更するだけで要素の色を変えることが可能です。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<!-- Sass のマップのキーを設定する -->
<body class="primary">
  <h1 class="title">タイトル</h1>
  <button type="button" class="btn">ボタン</button>
</body>
</html>
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?