Skip to content

Instantly share code, notes, and snippets.

@nemoDreamer
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemoDreamer/a6fd615ad97f59e7b983 to your computer and use it in GitHub Desktop.
Save nemoDreamer/a6fd615ad97f59e7b983 to your computer and use it in GitHub Desktop.
User function approximation in server-side LESS (and a true greyscale "function")
@color: #f88;
/* LESS admits that their greyscale function doesn't respect relative lightness */
.bad_grayscale {
original-color: @color;
desaturated: desaturate(@color, 100%);
greyscaled: greyscale(@color); // synonymous
}
/* so let's FIX that! */
.greyscale(@color; @keyword: color) {
@{keyword}: hsl(0, 0, luma(@color));
}
.usage_one {
.greyscale(@color);
}
.usage_two {
.greyscale(@color, background-color);
.greyscale(#f00, border-color);
}
.bad_grayscale {
original-color: #ff8888;
desaturated: #c3c3c3;
greyscaled: #c3c3c3;
}
.usage_one {
color: #a1a1a1;
}
.usage_two {
background-color: #a1a1a1;
border-color: #363636;
}
@nemoDreamer
Copy link
Author

Unless you are using LESS client-side, you can’t define your own functions (similar to max() or lighten()) that return a value.

As a reminder, client-side usage works as follows:

less = {
  functions: {
    myfunc: function() {
      return new(less.tree.Dimension)(1);
    }
  }
};

Here’s an elegant server-side solution that — while not giving you return values — does give us a close approximation of a user function in LESS. As you can see, we’re using variable interpolation and default values on a function mixin to achieve a pretty flexible result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment