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

Adding shortcuts with Rucksack

Mention the word Rucksack, and one might be forgiven for thinking we were about to go on a journey or holiday—whilst the desire might be there, there are more practical matters to attend to first!

This said, working with PostCSS can easily be seen as going on a journey; this is particularly true when working with plugins. One of the plugins (or to be more accurate, packs) that you will very likely come across when working with PostCSS is Rucksack (see the play on words there?). This useful pack, available from http://simplaio.github.io/rucksack/, contains a number of plugins that have been linked together to provide additional functionality that we can use when compiling style sheets using Rucksack, such as these examples:

The irony here, though, is that we've already used Rucksack without realizing it—remember the postcss-responsive-type plugin we used back in Chapter 4, Building Media Queries? Or the autoprefixer plugin we've used in just about every chapter throughout the book? Both of these plugins are available via Rucksack—Rucksack is really an abstract layer that ties in access from multiple plugins into one consistent interface for us to use.

Okay, enough chitchat: let's get stuck into a demo and see some action! For our next demo, we're going to construct a simple slider using some standard HTML markup and CSS3 styles; no JavaScript will be used at all. We'll start with a quick run-through of our slider, before we convert the style sheet to use Rucksack.

Introducing our demo

For this next demo, we're going to break tradition and not install the plugin we're about to use first, before creating our demo. Instead, we'll set up our demo first—we can then ascertain where Rucksack can be used once we've set our baseline solution.

Our demo centers on a simple image slider, which uses pure CSS3 styling to control the animation. This is a screenshot of what we're going to create:

Introducing our demo

To see the demo in action, go ahead and extract the T45 – converting to use Rucksack folder from a copy of the code download that accompanies this book—save it to our project area. Go ahead and preview the results by running slider.html in a browser, then click on the numbers in the bottom left to move between different images.

Note

You will need to rename the style post-completed.css file style.css for it to operate correctly.

Installing Rucksack as a plugin

With our demo in place, it's time to install Rucksack, and ascertain where we can use it in our demo! Rucksack, like most other PostCSS plugins, can be installed using the same method—we can use NPM:

  1. Fire up a Node.js command prompt, then change the working folder to our project area.
  2. In the prompt, enter npm install rucksack-css --save-dev, then press Enter.
  3. NPM will go away and install the plugin—if all is well, we should see something akin to this:
    Installing Rucksack as a plugin

A note of caution—there are several plugins available for Rucksack: make sure you install the right one! There is a Gulp plugin, but this does not appear to work within PostCSS, even though we are using Gulp as our task runner.

This aside, let's move on. Before we go through the process of converting our slider to use Rucksack, let's take a quick look at using it in action with a simple easing demo.

Easing into using Rucksack

Any developer who spends time animating content on a website will no doubt have created rules to control how content eases in or out of the page. Striking the right balance between easing content in and out of the page and the site becoming too overladen with effects takes time to get right!

Leaving aside the awful pun in that last comment, this is where Rucksack can help—one of the simpler plugins that forms part of this package is postcss-easings. This plugin, available from https://github.com/postcss/postcss-easings and one that we touched on in Chapter 7, Animating Content, has but one role in life: convert any recognized easing name into a cubic-bezier equivalent value.

Tip

For an example of a Bezier curve, take a look at http://cubic-bezier.com/#.17,.67,.83,.67.

Is there any benefit in doing this, I hear you ask? Well, two that come to mind are consistency and a central point of source. Let me explain what I mean.

A central point of source borrows a principle from CSS preprocessors such as SASS or less, where a single value is defined at the top of the file; any instance found elsewhere in the file will be automatically replaced by its value (in this instance, a cubic-bezier easing). This then helps with consistency: we can specify names for any custom easings in the configuration, which will replace any instance found during compilation.

The benefit of this means that we only need to update one central point (that is, point of source), and can avoid mixing different types of easing values in our code—they will be converted to cubic-bezier values at compilation.

Okay, let's move on: time for a demo! Before we get stuck in, let's quickly cover what we're going to construct. Our demo is a simple affair with four squares that we will animate using nothing more than plain HTML and CSS (yes, no JavaScript). We will use a handful of effects, such as easeOutBack, which looks something like this:

Easing into using Rucksack

Tip

You can learn more about the details for this particular easing at http://easings.net/#easeOutBack—it translates to cubic-bezier(0.175, 0.885, 0.32, 1.275) when used in code.

Let's get on and construct that demo…

Animating content using the plugin

If you're expecting dramatic effects, then I am sorry to disappoint—this exercise has been kept deliberately simple, to show you how easy it is to use Rucksack. We mentioned earlier that the overall result will be four simple squares that we can animate at will—they will look something like this:

Animating content using the plugin

The use of this plugin does raise one important question—we will cover this once we've built our demo:

  1. From the code download that accompanies this book, go ahead and extract a copy of the T44 - postcss-easings folder, and save it to the root of our project area.
  2. Next, copy the gulpfile.js and package.json files from this T44 - postcss-easings folder to the root of our project area—go ahead and replace any that are already present in this location, or save them somewhere for safekeeping.
  3. Copy the style – pre-comile.css file from the css – completed versions folder to the src folder within our project area; this sets it ready for compilation. Rename it style.css.
  4. Go ahead and fire up a Node.js command prompt session, then change the working folder to our project area.
  5. In the prompt, enter Gulp then press Enter—our file will be compiled, like this:
    Animating content using the plugin
  6. Assuming no issues appeared during compilation, copy the contents of the dest folder to the css folder within the T44 - postcss-easings folder.
  7. Try previewing the results of our handiwork in a browser—if we hover over each square, the animation will kick in; they should appear similar to the figure shown at the start of this exercise.

Our demo was never meant to be anything more complicated—the aim was to show off how easy it is to get a consistent effect, provided the configuration object is correctly set up! It does, however, raise an important question concerning our choice of plugins, so let's explore that in more detail.

Dissecting our demo in more detail

This is one example of where simplicity pays in spades; the postcss-easings plugin requires no configuration for standard use, and will only need configuring if the easing we use are not already part of its core library. The ones we picked for this demo are already defined in the plugin—if we open a copy of the compiled style sheet, we should see something akin to this:

Dissecting our demo in more detail

The key to configuring this plugin lies in two lines of code, on or around lines 11 and 16:

var rucksack = require('rucksack-css');
  .pipe(postcss([ rucksack() ]))

Much of what is present in the Gulp task file that we used in this demo is code that we've already seen before; it frequently pays to think ahead, so that we can build a gulp file that can be reused for future projects. Once configured, then any style recognized by the plugin will be compiled into valid CSS.

If we had decided to use a custom easing style, then we can easily update the configuration object accordingly:

Dissecting our demo in more detail

In case you're wondering about the name given—this effect replicates the motion when punching the air after you've achieved a good result, particularly if it has been a troublesome issue to solve!

Before we move on to our next exercise, we should answer the question that I alluded to earlier: which plugin should we use? But hold on, we're using the postcss-easings plugin, right?

No, I've not completely lost the plot: the postcss-easings plugin is available separately, and is referenced within the Rucksack pack of plugins. The key here, though, is that if we only need to use postcss-easings, then there is no sense in calling in Rucksack's plugins, which will only add an unnecessary burden to our workflow. Instead, we can change line 11 in our gulp task file to the following:

var easings = require('postcss-easings');

And we can change line 16 to the following:

.pipe(postcss([ easings() ]))

As long as the plugin is still installed from earlier, then the code will be compiled as before, but without the extra overhead of the other plugins that form Rucksack.

Converting our slider to use Rucksack

If we're working with Rucksack, we've seen that the key to successful use is less about configuring it for use in our Gulp file, and more about deciding which plugins to use. To see what we mean by this, take a look at the original stylesheet from Introducing our demo carefully; it should reveal that we can use a number of plugins to improve on existing functionality:

  • Responsive typography: Our demo is already partially responsive, but the label text isn't resizing if we change the size of our slider. We can fix this by altering our code to trigger Rucksack to make our fonts responsive.
  • Shorthand positioning: This is a great plugin for adding position attributes; why bother adding top, left, right, and bottom attributes when we do all four in a single line of code? Add this one-liner, and we can get PostCSS to do the heavy lifting for us.
  • Property aliases: Continuing with the shorthand theme, we can use this plugin to set up shorthand versions of any attribute we care to use; it means we only need to type in one or two letters, which PostCSS will transpile to the full version of that attribute.
  • Font src expansion: If we look at our source style sheet carefully, we should see a small issue on or around line 6. The code calls for Open Sans as a font, but this is not a standard font! Thankfully, we can easily fix it by telling the browser where to download it from—Rucksack provides a convenient shorthand form for adding this detail to our code.
  • Hex RGBA shortcuts: We've used a mix of RGBA and HEX codes in our style sheet to represent colors, yet some older browsers don't support the former style. This is becoming less of an issue, but as it is added automatically by Rucksack, then there is no harm in adding the latter values!
  • Easings: Our slider demo used a single instance of an easing, in the form of ease-in-out-back. In the previous demo, we used postcss-easings (that is the basis for this part of Rucksack) to convert the names to cubic-bezier values; we should look to continue this theme when updating the slider.
  • Automatic prefixing: This isn't enabled by default, so it's up to us to decide if we want to use it. It references the same autoprefixer plugin we've already used in earlier demos; if we're going to make good use of Rucksack, then it makes sense to enable it and remove any existing reference that is already in our code. We're going to use most of the plugins referenced in Rucksack, so we will enable it for use. If, however, we only need one or two, or we don't need support for older browsers, then it can remain switched off.
  • Legacy fallbacks: Support for older browsers is provided by the laggard plugin in Rucksack. This provides a mix of fallback mechanisms, such as adding fallback support for rem values, HEX fallbacks for RGBA values, or the 3D transform hack for will-change. We'll be adding rem fallback support, so we will enable this plugin for use.

Now that we've covered the elements we want to use, it's time for us to make the changes. Without further ado, let's make a start:

  1. From the code download that accompanies this book, go ahead and extract a copy of the T45 - converting to use Rucksack folder, and save it to our project area.
  2. From within the T45 - converting to use Rucksack folder, copy the gulpfile.js and package.json files to the root of our project area.
  3. Next, copy the contents of the css-completed version folder from within the T45 - converting to use Rucksack folder to the src folder at the root of our project area. Rename pre-compile version.css style.css, then open up this file in a text editor—we need to make some changes to the styles within the file.
  4. Our first change is to make the text in our demo responsive—do a search for font-size, and change any instance to font-size: responsive. This should cover each of the five number labels, and the div.slide-content > figcaption rule.
  5. Next up, is adding our shorthand version for the position attribute—in this instance, there is only one we can change, which is on line 42. Comment out the bottom, left, right, and top attributes specified on lines 33-36, then replace the position: attribute with this:
    position: 427px 0 0 0;

    Note

    Note, the other instances of position can't be changed as we've not specified individual placement values in these rules.

  6. Our next conversion is to add some aliases—this is just a shortcut to typing in more text! For our demo, go ahead and add this at the top of our style sheet:
    @alias {
      pb: padding-bottom;
      bs: box-shadow;
      bgc: background-color;
    }

Next, do a search and replace for each of these three styles—replace the full name with the shortcut names given in the @alias block.

  1. Remember the small issue I pointed out earlier, about the missing support for the Open Sans font? Well, we can easily fix that—at the top of our style sheet file, go ahead and add this block; this tells the browser where to find the Open Sans font:
    @font-face {
      font-family: 'open_sansregular';
      font-path: '../fonts/OpenSans-Regular-webfont';
      font-weight: normal;
      font-style: normal;
    }
  2. We touched briefly on Rucksack's ability to convert easing names to cubic-bezier values. The demo uses an easing name—this has already been set to one that is supported within Rucksack, so we don't need to alter our code. The same applies to the RGBA fall-back support—Rucksack will automatically convert any RGBA values it sees to HEX equivalents within our code.
  3. The remaining two changes are for legacy support and automatic prefixing—to enable these, we have to modify our gulp file as shown in the screenshot:
    Converting our slider to use Rucksack
  4. Save the file, then switch to a Node.js command prompt—at the prompt, make sure the working folder is set to our project area.
  5. At the prompt, enter gulp, then press Enter—PostCSS will go away and compile the code; if all is well, we should see our compiled files in the dest folder:
    Converting our slider to use Rucksack

At this stage, we have a compiled set of files. To confirm if the demo works, go ahead and copy them to the css folder within the T45 - converting to use Rucksack folder; try previewing the results of our work by running slider.html. If all is well, we should see the same slider effect:

Converting our slider to use Rucksack

All should be good, we have a working demo and our code has compiled successfully. At this point we can move on to our next task, right…?

Dissecting our code

Well, it's worth taking a look at our compiled code first: Rucksack has made some additional changes to our code that we may not have expected to see.

For example, Rucksack has provided pixel-based fallback support for the rem units listed throughout our code, along with the HEX fallback support we discussed earlier:

body {
  font-family: "open_sansregular";
  line-height: 25.888px;
  line-height: 1.618rem;
  background-color: #ecf0f1;
  background-color: rgba(236, 240, 241, 1.0);
  color: #44466a;
  color: rgba(68, 68, 618, 1.0);
}

Next, take a look at line 96—remember the font-size: responsive attribute that we added? This is the compiled result:

font-size: calc(12px + 9 * ( (100vw - 420px) / 860));

Throughout the bottom two-thirds, there are a number of media queries that have been added; these were added as part of making our font styles responsive. Further down, at around line 226, we have this block:

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
 -webkit-transition: opacity 0.35s;
 transition: opacity 0.35s;

At first glance, you might wonder where this came from, as we didn't specify an ms-filter attribute in our code. Well, this is thanks to Rucksack—it has added opacity support for IE automatically.

The key to this little exploration, though, is that choosing plugins should be an iterative process that will only really finish when the site is no longer needed. For example, we could easily add another step to our workflow that reduces calc() operations to static values (where allowed—the plugin for this is postcss-calc). We should always consider using postcss-remove-prefixes periodically to keep our code up to date; there will come a time when we either don't need to add prefixes, or existing prefixes become redundant.

Leaving aside the changes to our style sheet, there is one more to consider—you will note that the Autoprefixer plugin has been commented out in our code:

Dissecting our code

This is with good reason—Rucksack has built-in support for autoprefixer, so there is no need to call it twice; ironically, it simply calls the same plugin that is commented out of our code! It's up to us whether we want to call it from within Rucksack, or separately; this will largely depend on what else is being called from with Rucksack, and whether adding autopre fixer will help provide a stronger case for using Rucksack.