Table of Contents for
Mastering PostCSS for Web Design

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering PostCSS for Web Design by Alex Libby Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. Mastering PostCSS for Web Design
  4. Mastering PostCSS for Web Design
  5. Credits
  6. About the Author
  7. About the Reviewer
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Conventions
  13. Reader feedback
  14. Customer support
  15. 1. Introducing PostCSS
  16. Introducing PostCSS
  17. Setting up a development environment
  18. Creating a simple example using PostCSS
  19. Linting code using plugins
  20. Exploring how PostCSS works
  21. Summary
  22. 2. Creating Variables and Mixins
  23. Creating a hover effect example
  24. Transitioning to using PostCSS
  25. Adding variable support to PostCSS
  26. Updating our hover effect demo
  27. Setting the order of plugins
  28. Creating mixins with PostCSS
  29. Looping content with PostCSS
  30. Summary
  31. 3. Nesting Rules
  32. Navigating through pages
  33. Transitioning to using PostCSS plugins
  34. Exploring the pitfalls of nesting
  35. Making the switch to BEM
  36. Exploring our changes in more detail
  37. Summary
  38. 4. Building Media Queries
  39. Exploring custom media queries in PostCSS
  40. Making images responsive
  41. Adding responsive text support
  42. Optimizing media queries
  43. Retrofitting support for older browsers
  44. Moving away from responsive design
  45. Taking things further with CSS4
  46. Summary
  47. 5. Managing Colors, Images, and Fonts
  48. Managing fonts with PostCSS
  49. Creating image sprites
  50. Working with SVG in PostCSS
  51. Adding support for WebP images
  52. Manipulating colors and color palettes
  53. Creating color functions with PostCSS
  54. Summary
  55. 6. Creating Grids
  56. Creating an example with Bourbon Neat
  57. Exploring the grid plugins in PostCSS
  58. Transitioning to using PostCSS-Neat
  59. Creating a site using Neat and PostCSS
  60. Adding responsive capabilities
  61. Summary
  62. 7. Animating Elements
  63. Moving away from jQuery
  64. Making use of pre-built libraries
  65. Switching to using SASS
  66. Making the switch to PostCSS
  67. Exploring plugin options within PostCSS
  68. Updating code to use PostCSS
  69. Creating a demo in PostCSS
  70. Optimizing our animations
  71. Using our own animation plugin
  72. Summary
  73. 8. Creating PostCSS Plugins
  74. Dissecting the architecture of a standard plugin
  75. Creating an transition plugin
  76. Building a custom font plugin
  77. Simplifying the development process
  78. Guidelines for plugin building
  79. Making the plugin available for use
  80. Summary
  81. 9. Working with Shortcuts, Fallbacks, and Packs
  82. Exploring plugin packs for PostCSS
  83. Adding shortcuts with Rucksack
  84. Linting and optimizing your code
  85. Providing fallback support
  86. Summary
  87. 10. Building a Custom Processor
  88. Exploring our processor
  89. Dissecting issues with our processor
  90. Optimizing the output
  91. Adding reload capabilities
  92. Extending our processor further
  93. Testing the final pre-processor
  94. Getting started with some hints and tips
  95. Introducing the CSStyle library
  96. Summary
  97. 11. Manipulating Custom Syntaxes
  98. Preparing our environment
  99. Implementing custom syntax plugins
  100. Parsing CSS
  101. Formatting the output with the API
  102. Highlighting our syntax code
  103. Summary
  104. 12. Mixing Preprocessors
  105. Exploring the conversion process
  106. Introducing the Pleeease library
  107. Compiling with other preprocessors
  108. Using the PreCSS library
  109. Converting a WordPress installation
  110. Setting up our environment
  111. Considering the conversion process
  112. Making changes to our code
  113. Compiling and testing the changes
  114. Summary
  115. 13. Troubleshooting PostCSS Issues
  116. Exploring some common issues
  117. Getting help from others
  118. Summary
  119. 14. Preparing for the Future
  120. Converting CSS4 styles for use
  121. Supporting future syntax with cssnext
  122. Creating plugins to provide extra CSS4 support
  123. Summary
  124. Index

Creating color functions with PostCSS

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.

Adjusting colors using functions

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:

Adjusting colors using functions

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:

  1. We start by extracting a copy of the Tutorial25 folder from within the code download that accompanies this book—go ahead and save this to our project area.
  2. If the project area already has a package.json and/or a gulpfile.js present, then remove them; replace them with the files from within the Tutorial25 folder.
  3. Although we have the right configuration files in place, we still need to install the plugin—go ahead and fire up a Node.js command prompt session, then change the working folder to our project area.
  4. At the prompt, enter these commands, pressing Enter after each:
    npm install postcss-color-function --save-dev
    npm install css-color-converter --save-dev
    
  5. At this point, we can now go ahead and compile our style sheet—look for 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.
  6. Switch to the Node.js command prompt from earlier, then enter gulp at the prompt and press Enter.
  7. If all is well, we should see the by now compiled style sheets appear (both uncompressed and minified), along with the source map in the 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?

Dissecting our demo

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!

Creating colors with PostCSS filters

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:

Creating colors with PostCSS filters

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:

  1. We'll start by extracting a copy of the Tutorial26 folder from the code download that accompanies this book; save it to the root of our project area.
  2. Next, go ahead and remove any copies of gulpfile.js and package.json from the root of our project area.
  3. From the Tutorial26 folder, copy both package.json and gulpfile.js to the root of our project area.
  4. With these files in place, we still need to install the plugins. In a Node.js command prompt window, change the working folder to our project, then enter these commands, and press Enter after each:
    npm install postcss-functions --save-dev
    npm install css-color-converter --save-dev
    
  5. From the Tutorial26 folder, copy style – pre-compile.css to the src folder in the project area; rename it to style.css.
  6. Revert back to the Node.js command prompt window, then at the prompt, enter gulp and press Enter.
  7. If all is well, we should see a source map and two compiled style sheets appear in the dest folder; copy these to the css folder within the Tutorial26 folder.
  8. Try running the demo in a browser. If all is well, we should see four boxes appear, with various shades of red, as shown at the start of this exercise.

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.

Exploring our demo 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.

Tip

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/.

Comparing with CSS3 filters

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 is a great library, and produces some wonderful effects, but it is an external dependency; we run the risk that development may be discontinued in the future, which might have an impact on our code.
  • Using PostCSS means that we can remove the dependency on external libraries, we are in control over which effects should be included, and which are surplus to requirements. If we use a library such as CamanJS, then we may be forced to include lots of extra baggage that unnecessarily inflates our code.
  • Not every browser will support standard CSS3 filters—using PostCSS gives us an opportunity to design our own filters that can apply similar effects.
  • We can always use existing processors, such as SASS, but again we have a dependency on an external library; using PostCSS means we can still apply the same principles, but without the dependency.

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.

Adding Instagram effects to your images

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:

  1. We'll begin, as always, by extracting a copy of the Tutorial27 folder from the code download that accompanies this book—save this to the project area.
  2. Next, extract copies of gulpfile.js and package.json, replace any that are stored at the root of our project area, with these new copies.
  3. We now need to install the postcss-instagram plugin, so go ahead and fire up a Node.js command prompt session, then change the working folder to our project area.
  4. At the prompt, go ahead and enter this command, then press Enter:
    npm install postcss-instagram --save-dev
    
  5. Copy the style – pre-compile.css file to the src folder at the root of our project area, then rename it as style.css.
  6. Once the plugin is installed, enter gulp at the prompt, then press Enter.
  7. PostCSS will go away and compile our code, if all is well, we should see the usual files appear in the 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:

Adding Instagram effects to your images

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:

Adding Instagram effects to your images

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:

Adding Instagram effects to your images

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.