LoginSignup
6
3

More than 5 years have passed since last update.

Sassでeachを用いた色管理でハマった(Always quote color names when using them as strings)

Posted at

やりたいこと

webサービスのデザインにルールを設けるために、色をあらかじめ決めておくのはあるあるだと思います。
その管理を楽にすべく、Sassで変数に色コードを指定しておくのもまたあるある。

$main-color: #e73562;
$sub-color: #14be6b;

こんな感じですね

そして、これらをいろんな部分でbackground-colorcolorに用いることも多く、一気に管理する方法としてSassで@eachを利用する方法もあります。

$red: #e73562;
$blue: #4169e1;
$green: #14be6b;

$app-colors: (
  red: $red,
  blue: $blue,
  green: $green
);

@each $name, $color in $app-colors {
  .bg-#{$name} {
    background-color: $color;
  }
  .text-#{$name} {
    color: $color;
  }
}

一気に定義できて便利ですが、実はこのコードは期待通りに動きません。

起きたエラー(Warning)

エラーではなくWarningなのでコンパイルはできますが、期待した通りには動きません。
こんなメッセージが表示されます。

WARNING on line 37, column 4 of /hoge/coupon_rep/app/assets/stylesheets/common/_color.scss:
You probably don't mean to use the color value `red' in interpolation here.
It may end up represented as #ff0000, which will likely produce invalid CSS.
Always quote color names when using them as strings (for example, "red").
If you really want to use the color value here, use `"" + $name'.

解決方法

$app-colors: (
  red: $red,
  blue: $blue,
  green: $green
);

↑これを
↓こうします。

$app-colors: (
  'red': $red,
  'blue': $blue,
  'green': $green
);

どういうわけか

sassのgithubリポジトリでissueが立っていました。参考

This is not a bug. As the warning says, an unquoted color name refers to the color object, not the string. Use quotes for your map keys.

とあるように、クオーテーションで囲まれていない色の名前があったとき、それは「red」という文字ではなく、「#ff0000」というredの色コードとして扱われるそうです。
ということは、最初の指定方法でコンパイルすると以下のようになるということですね。

.bg-#ff0000 {
  color: #ff0000;
}

Warningを出してくれてありがたいですね!
みなさんも気をつけてください!

6
3
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
6
3