CSS Front-End Development LESS

Authored by Dustin Horton

Leveraging LESS Color Functions for Better CSS3 Gradient Fallbacks in IE

Until IE 10 is the baseline for websites you’re building, you’re going to need to provide a background fallback for browsers that don’t support CSS3 gradients. If design integrity or browser consistency are of the utmost concern, then you’ll likely want to use a fallback image, but in my work I’ll often choose to to fallback to a color, primarily to keep code terse and the site more maintainable.

When using CSS3 gradient generators, such as CSS3 Please, they’ll often provide a fallback that’s either the starting or ending color of the gradient. For example, with a gradient of white to red, CSS3 Please provides a fallback of white.

Depending on the design, this might be fine…but it’s likely you want something closer to the CSS3 gradient.

Alternatively, you could pick a hex from within the gradient yourself. There’s two issues with this strategy:

  1. Time to choose a color – each gradient will require choosing different fallback hex
  2. Actually choosing a color – it’s not easy to know what the midpoint of a gradient is, even with a tool like Photoshop. You likely know that #aaa is 50% grey, but who knows offhand what the midpoint between #2a2a9a & #c72dd6 is

The LESS mix() Color Function

LESS has several color functions for manipulating color, and for CSS3 gradient fallbacks, mix() does just the trick.

As its name would suggest, mix takes two colors, ‘mixes’ them, and outputs the results.

Be forwarned: the LESS docs incorrectly show the mix function as taking only 2 parameters, but this will not compile. The function requires a third parameter, which is the percentage of each color.

So in use, this complete mixin could more accurately fallback for < IE 9: [gist id="f9d14f3b86009ad1b132" file="gradient-fallbacks-03.less" /]