Can I convert a short form color (#123) into the long form (#112233) in stylus?


So I'm using an IE specific filter that requires the colours to be in the long form of 6 characters. But I have a thousand line stylesheet filled with calls to my function using the short form of 3 characters. So I'm hoping that it's possible to convert from the short to the long form from within the function. Any built-in or custom function will do. My function looks something like this:

td_gradient(color1, color2)
    background-color (color1 + (color2 - color1) / 2)
    background -webkit-gradient(linear, 0% 0%, 0% 100%, from(color1), to(color2))
    background -webkit-linear-gradient(top, color1, color2)
    background -moz-linear-gradient(top, color1, color2)
    background -ms-linear-gradient(top, color1, color2)
    background -o-linear-gradient(top, color1, color2)
    filter s("progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorstr='%s', EndColorstr='%s')", color1, color2)

The input colours look like #333 and #123, but the Microsoft filter function requires #333333 and #112233. Is there any way to satisfy it without editing every instance or a colour in my stylesheet?

Problem courtesy of: Hubro


Looking at the stylus source code, in lib/nodes/rgba.js, there's this method: RGBA.prototype.toString. On line 268, we find:

if (r[0] == r[1] && g[0] == g[1] && b[0] == b[1]) {
  return '#' + r[0] + g[0] + b[0];
} else {
  return '#' + r + g + b;

I experimented with building a function for you, but I can't seem to get the color back as a string, to do string manipulation. So the easiest way for you would probably be to patch RGBA.prototype and remove this shortening.

UPDATE: Ok, here is a function for you:

module.exports = function() {
    var hex = function(n) { return n.toString(16) };

    return function(style) {
        style.define('longColor', function(color) {
            return '#' + [color.r, color.g, color.b].map(hex).join("");

If you put it in a file color.js, you can use it with stylus -u ./color.js, or stylus' javascript API with use. Stylus usage:

  color longColor(#333)
Solution courtesy of: Linus Gustav Larsson Thiel


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.