In our journey through manipulating colors using PostCSS, we've so far seen how to define colors using palettes—this may work in some instances, but there will be occasions when we need to specify a color that doesn't feature in a palette.
We can always try to specify the value manually, but what happens if we need to alter it? Do we try to find every instance of it, and risk the possibility of missing an instance?
The answer is no. Instead, we can use the postcss-color-function plugin to create our colors dynamically; we can then assign the resulting value to a variable if we find ourselves frequently using this color. We can use this route to produce some nice shades of colors, so let's get stuck in and explore using this plugin in more detail.
A useful facility within most CSS preprocessors is the ability to create new colors dynamically, we can do this either by adjusting a color channel, or applying a filter effect to the color, such as making it darker:

The benefit of this is simple, it allows us to reduce the number of base colors we assign by default; the remaining colors can be created automatically. If we need to change one of our base colors, then any colors created dynamically should still work.
Thankfully, we can achieve the same effects within PostCSS, to do this, we need to make use of the postcss-color-function plugin, available from https://github.com/postcss/postcss-color-function. We'll also be using the css-color-converter plugin, to help manage conversion between different color formats.
Let's explore this in more detail with a simple demo:
Tutorial25 folder from within the code download that accompanies this book—go ahead and save this to our project area.package.json and/or a gulpfile.js present, then remove them; replace them with the files from within the Tutorial25 folder.npm install postcss-color-function --save-dev npm install css-color-converter --save-dev
styles – pre-compile.css from within the css – completed version subfolder, and save it to the src folder within our project area as style.css.gulp at the prompt and press Enter.dest folder. Copy the contents of this folder to the css folder within the Tutorial25 folder.Try previewing the results within a browser, if the compilation was successful, we should see four boxes with different shades of red appear, as shown at the start of this exercise. The question is though, we've seen the results appear, but how does PostCSS know to create these colors?
It's a good question, the conversion process is very simple; the trick to it, though, lies not within compiling, but working out how to achieve the color! Odd as it may seem, choosing the color isn't as easy as it looks; let me explain more:
The compilation process is, like other PostCSS plugins, very easy to configure—we begin of course with creating a variable that defines the color-function plugin:
var colorfunction = require('postcss-color-function');Next up, we add a reference to our principal gulp task, here we've used both autoprefixer and the color-function plugin together, but the former isn't strictly needed, as we're not adding any vendor prefixes:
gulp.task('autoprefixer', function() {
return gulp.src('src/*.css')
.pipe(postcss([ autoprefixer, colorfunction() ]))
.pipe(gulp.dest('dest/'));
});The real magic, though, is in the colors we assign within our style sheet—our first box is a control, with a standard red color:
#box0 { background-color: #ff0000; }Next up, we're adding a tint of 60% to box1, which has the effect of turning it a light pink:
#box1 { background-color: color(red tint(60%)); }
Box2 goes the other way, even though we've used a lightness filter (where you might expect a similar result as box1), the negative number makes it a brown-red color:
#box2 { background-color: color(red lightness(-20%)); }The final box, box3, continues the brown theme from box2, but makes it lighter. Note though, that in the comment, this shade is what would be produced if we had applied a sepia tone:
#box3 { background-color: sepia(red, 0.7);}The question is, how would we know that this is indeed a sepia filter being applied?
At face value, it looks like we've selected red, then altered each channel by a specific amount to get the final result.
A drawback of using this plugin is that it doesn't have functions to support all of the equivalent CSS3 filters available today; it does mean we have to be resourceful, and calculate what the color should be directly. We will be able to change that in the next demo—there will be occasions when we need to create our own custom filters; a good example is sepia. It does mean more work upfront, but it allows us to then call a sepia() function by name, rather than approximate the final result.
If you struggle to find what a color should be once a filter is applied, take a look at http://jackiebalzer.com/color; this is a great site that allows us to choose a color and see what the results are when filters are applied. It is written for SASS, but the end result will be identical for PostCSS. A site such as ColorHexa.com (http://www.colorhexa.com) is a good help too, we can use it to verify what color values should be when a filter has been applied.
On we go. We discovered during our exercise that the postcss-color-function plugin doesn't cover all of the CSS3 filters that we can use in CSS; for the sepia example, we had to assign a calculated color value, rather than applying a filter effect. Let's fix that now. With a bit of upfront rework to our demo, we can create our own custom functions. It means that if, for example, we want a sepia effect, then we can call sepia(), rather than calculate what the final color should be!
In our previous demo, we took a look at programmatically changing colors—this is a function that has been present in most CSS processors (such as SASS or Less) for some time.
There may be occasions where we require a finer degree of control over changing colors, and that simply using existing functions provided by the postcss-color-function plugin isn't sufficient, or that the desired filter isn't available. If we're feeling inclined, we can create our own color functions; for this, we can use the postcss-functions plugin, available from https://github.com/andyjansson/postcss-functions, to expose the use of JavaScript functions in our task file.
It's worth noting, though, that if a CSS3 filter doesn't exist, then most can be created using a combination of different calculations (such as the sepia example from the previous demo). This may technically work okay, but it is easier to simply reference a sepia filter by name, rather than work out that #box3 has a sepia effect applied!
I feel a demo coming on, so without further ado, here's a screenshot of what we're going to create:

In short, we're using a standard shade of red (#ff0000, just to be clear!), and calculating various shades using a tint, darken, or sepia filter.
Let's take a look at how to create these colors in more detail:
Tutorial26 folder from the code download that accompanies this book; save it to the root of our project area.gulpfile.js and package.json from the root of our project area.Tutorial26 folder, copy both package.json and gulpfile.js to the root of our project area.npm install postcss-functions --save-dev npm install css-color-converter --save-dev
Tutorial26 folder, copy style – pre-compile.css to the src folder in the project area; rename it to style.css.gulp and press Enter.dest folder; copy these to the css folder within the Tutorial26 folder.If we take a look at the contents of the gulp task file in more detail, it will look larger than previous exercises; it might look like we're doing more, but in reality, a lot of it we've already seen before, in earlier demos. Let's take a look at it in more detail.
If we open up our gulp task file, we can see it contains a number of functions, along with tasks that we've used in previous demos, such as lint-styles. The key in this demo is the three color functions, along with the main part of the autoprefixer task.
Let's start with the color functions, using darkenColor as our example:
function darkenColor (value, frac) {
var darken = 1 - parseFloat(frac);
var rgba = color(value).toRgbaArray();
var r = rgba[0] * darken;
var g = rgba[1] * darken;
var b = rgba[2] * darken;
return color([r,g,b]).toHexString();
}We begin by extracting the decimal value, then subtracting it (as frac) from 1. This gives us our adjust value, or the value by how much we will darken our colors. Next up, we convert the color used (in this case, red) to a valid RGBA value, and split it into the RGBA array. We then multiply each array value from rgba by the darken value, and reform it as a valid color, before converting it to a HEX value.
Once each function has been created, we can then reference it from our gulp task, as shown:
gulp.task('autoprefixer', function() {
return gulp.src('src/*.css')
.pipe(postcss([ autoprefixer, functions({
functions: {
tint: tintColor,
darken: darkenColor,
sepia: sepiaColor
}
})
]))
.pipe(gulp.dest('dest/'));
});All of the functions use a similar process, but the main calculations that use the values from the rgba[] array, such as adding a tint (tintColor), or working in a sepia effect (sepiaColor), will be different.
The question you may ask though, is where do we get the calculations from? Well, there are plenty of sources available on the Internet, such as this link on Stack Overflow: http://stackoverflow.com/questions/6615002/given-an-rgb-value-how-do-i-create-a-tint-or-shade. Another alternative that may be worth a look is on Chris Coyier's CSS Tricks site, at https://css-tricks.com/snippets/javascript/lighten-darken-color/. In reality though, the best site I've seen so far is in the CamanJS library, at http://www.camanjs.com; the examples in this demo are based on the functions available from this library at http://camanjs.com/docs/filters.html.
A useful little tip, if you want to check what color values should be displayed for a particular tint or shade, is to check out http://highintegritydesign.com/tools/tinter-shader/.
A key question we must ask at this stage is "why should we go through the effort of creating individual functions, when we could easily use a library such as CamanJS?"
Well, there are some key reasons for taking the route that we used in our demo:
CamanJS, then we may be forced to include lots of extra baggage that unnecessarily inflates our code.The key here, though, is that filter support in browsers is very good, save for IE—we should always consider using CSS3 filters first, but can look to create an IE-specific style sheet that allows us to use our own versions from within PostCSS.
Creating filters with PostCSS shouldn't be all boring though, we can absolutely have some fun with filters! A quick and easy way to apply some additional style to an image is through the use of Instagram filters—thankfully there is a pre-built plugin we can use for this purpose.
Enter the Instagram plugin, available from https://github.com/azat-io/postcss-instagram. Let's get stuck in and create a simple demo:
Tutorial27 folder from the code download that accompanies this book—save this to the project area.gulpfile.js and package.json, replace any that are stored at the root of our project area, with these new copies.postcss-instagram plugin, so go ahead and fire up a Node.js command prompt session, then change the working folder to our project area.npm install postcss-instagram --save-dev
style – pre-compile.css file to the src folder at the root of our project area, then rename it as style.css.gulp at the prompt, then press Enter.dest folder; copy these to the css folder within the Tutorial27 folder.At this point, if we try to preview the results in a browser, we should see something akin to this screenshot:

The key to this is in the main CSS style sheet, we can apply the required filter using nothing more than this within the rule:

This applies the 1977 filter (one of the filters available with the plugin). If we take a look at the compiled code, we can see that the plugin has added some additional rules; one to take care of creating the filter, and two to take care of positioning the filter on top of the image.
If we take a look at the compiled code, we can see the changes made by the plugin:

If you really want to get into the depths, then it's worth taking a look at the source code for this plugin, at https://github.com/azat-io/postcss-instagram/blob/master/index.js. It is fairly complex, but if you look carefully, you can see signs of the filter code that is used to apply the effect to our images.