lessprepros

Short-hand hexadecimal value converted to full hexadecimal value, Less preprocessing


I've been experiencing a syntax issue with Less preprocessing tools like Koala and Prepros (OSX 10.10.5, Yosemite) where a color value I've defined in short-hand hexadecimal (e.g. #fff, #000, etc.) will output as #fffffff or #000000 in the final .css file.

Here's a simple example of what I've observed:

// In variables.less (css-preprocessed/variables.less)
@white: #fff;

// In styles.less (css-preprocessed/application/less/styles.less)
@import '../../variables.less';
.container {
    background-color: @white;
}

// In styles.css (css-preprocessed/application/css/styles.css)
.container {
    background-color: #ffffff;
}

Please note, this issue is fairly recent. I have not augmented any settings for these respective tools. Each are running out-of-box.


Solution

  • This has always been the behavior in the older versions of Less compiler. The shorthand color values always got converted to longhand hexadecimal values. This has been fixed as part of v 2.5.2 release and the values would now stay as shorthand if it was provided as one.

    From Less Changelog:

    Shorthand colors will stay shorthand

    So, if you upgrade the compiler to the latest version then this problem should go away automatically.

    In the latest version, the following Less code: [Try it]

    @white: #fff;
    .container {
      background-color: @white;
    }
    

    would compile to

    .container {
      background-color: #fff;
    }
    

    Note: If you are using a ported version of the Less compiler (say Less4j or LessPHP) then you may have to check their change logs also to see when this behavior was adopted by them (and raise a feature request if they haven't done so yet).


    In all the older versions, the shorthand colors would get converted to longhand form whenever

    If you can't upgrade the compiler version then the only way to avoid conversion to the longhand format would be to wrap the variable's value in quotes and escape while output. Doing this would make Less compiler treat it as a string and output the value as-is.

    In the older versions, the following Less code:

    @a: #fff;
    @b: "#fff";
    a{
      color-1: #fff;
      color-2: @a;
      color-3: ~"@{b}";
    }
    

    would compile to

    a {
      color-1: #fff;
      color-2: #ffffff; /* note how this is converted */
      color-3: #fff; /* while this isn't */
    }
    

    You should note that doing this would affect any color channel operations that you'd like to perform on the value and would require conversion to color object using color() function. I wouldn't recommend doing this just for avoiding what is essentially a very small problem.