Skip to main content

Sass converts hsla to hex incorrectly

I ran into an issue where Sass was converting hsla() values to hex incorrectly. It would take an input like this:

/* input.scss */
.subtle-blue {
  background-color: hsla(212, 50%, 50%, 10%);
}

And convert it into:

/* output.css */
.subtle-blue {
  background-color: #407bbf;
}

That is not the same color. When processing the input styles, Sass ignores the alpha (opacity) value and converts it into a standard hex.

You can see the different between the two values here:

hsla(212, 50%, 50%, 10%)
#407bbf

If you search around for an answer, you will find a few suggestions to use strings for hsl values or recreating the hsl and hsla functions in Sass. Neither of those seemed an idea solution.

Instead of changing how you declare hsl value or recreating the function, you can fix this issue by using decimal alpha values instead of percent. Going back to the original example, change 10% to 0.1:

/* Input Sass */
.subtle-blue {
  background-color: hsla(212, 50%, 50%, 0.1);
}

And Sass will convert it to alpha-supporting rgba:

/* Output css */
.subtle-blue {
  background-color: rgba(64, 123, 191, 0.1);
}

These values aren’t identical because math is required, but they’re infinitely closer than the non-alpha hex value:

hsla(212, 50%, 50%, 0.1)
rgba(64, 123, 191, 0.1)

You can see this behavior for yourself in this Sass playground but not in Sassmeister. So it may depend on the flavor and version of Sass that you are using.

But for a quick fix that doesn’t involve wading into the release notes of your dependencies, opt for decimal alpha values in hsla.

Happy styling!