Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Sass change the format of my colors?

Tags:

sass

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?

like image 726
Brandon Dorsey Avatar asked Apr 02 '13 06:04

Brandon Dorsey


1 Answers

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().

like image 144
cimmanon Avatar answered Oct 14 '22 18:10

cimmanon