Why does Sass change the format of my colors?

2019-01-03 00:25发布

Sass is outputting #000 and #fff as black and white color values in my css file. For example:

$color: #000;

.box {
    color: $color;
}

Outputs to:

.box {
  color: black;
}

Shouldn't output the hex values?

标签: sass
1条回答
手持菜刀,她持情操
2楼-- · 2019-01-03 00:55

How Sass treats colors varies depending on what version you're using. But there are a few common behaviors:

  • Sass will always maximize backwards compatibility whenever possible. Since keyword, hex, and rgba have the broadest browser support, all colors will be converted to one of those 3 formats, prioritizing towards either the keyword or hex. The rgba format will only be used if the color has alpha transparency (if you specify rgba(0, 0, 0, 100), Sass will convert it to either black or #000)
  • If Sass has to choose between using the keyword or hex formats, the one it will use will depend on the output settings. The compact or compressed modes will always convert to hex, the other formats will use the keyword.
  • Sass will convert hex colors to their 3-digit format in compressed mode (eg. #000000 will be output as #000).

Sass 3.3 and older

Sass only converts colors when they are used as variables or if they are not in one of the 3 formats as described above:

$color-hex: #000000;
$color-keyword: black;
$color-rgb: rgb(0, 0, 0);
$color-hsl: hsl(0, 0, 0);

.box-hex {
    color: $color-hex;
    background: #000000;
}

.box-keyword {
    color: $color-keyword;
    background: black;
}

.box-rgb {
    color: $color-rgb;
    background: rgb(0, 0, 0);
}

.box-hsl {
    color: $color-hsl;
    background: hsl(0, 0, 0);
}

Output:

.box-hex {
  color: black;
  background: #000000;
}

.box-keyword {
  color: black;
  background: black;
}

.box-rgb {
  color: black;
  background: black;
}

.box-hsl {
  color: black;
  background: black;
}

Sass 3.4 and later

The only change from 3.3 to 3.4 is that when using variables, Sass will preserve the format of your color... unless it is in something other than the keyword, hex, or rgba formats.

.box-hex {
  color: #000000;
  background: #000000;
}

But what if I really need a specific format?

If you absolutely must have a specific format, you can turn it into a string:

$color: #{'#F00'}; // or `unquote('#F00')`
.foo {
    color: $color;
}

Output:

.foo {
  color: #F00;
}

Just keep in mind that when you do this, your "color" will not work with color manipulation functions like lighten() or darken().

查看更多
登录 后发表回答