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

Making images responsive

A key element of making any site responsive has of course to be images—after all, we can always construct a site without images, but how effective would it really be?

Sure, one can always use a data Uniform Resource Identifier (URI) to convert images to CSS equivalents, but this is at the risk of dramatically inflating our style sheet to the point of it becoming impossible to manage. The reality is that we have to have some form of images—if we are to make them behave, we clearly need to ensure that they expand or contract in size, according to available screen estate.

The easiest way to adapt images for responsive layouts is to set a max-width value to 100%, along with height: auto and display: block, and remove any attribute that defines either a fixed height or width for that image element. We can make the changes manually, but this is time-consuming; instead, let's take a look at a PostCSS plugin that allows us to set these three values at compilation, by adding one single line of code to each image.

Making an image responsive with PostCSS

Adding responsive capabilities to a site using PostCSS is simple; it will depend largely on your requirements as to how we make the images responsive, but the two key plugins to look out for are postcss-responsive-images (available at https://github.com/azat-io/postcss-responsive-images), and postcss-at2x (available at https://github.com/simonsmith/postcss-at2x).

We will cover the use of the postcss-at2x plugin in a moment, but for now, let's take a look at using the postcss-re sponsive-images plugin.

Implementing responsive capabilities to images

Making our images responsive requires a single line of code to be added to any image-based rule; let's dive in and add this capability to a copy of the Tutorial13 folder from the code download that accompanies this book:

  1. We'll start, as always, by installing the plugin—for this, fire up a Node.js command prompt, then run the commands as shown in this screenshot:
    Implementing responsive capabilities to images
  2. We'll start by extracting a copy of the Tutorial13 folder from the code download that accompanies this book, then saving it to our project area.
  3. Open up style.css from the css folder within the Tutorial13 folder, then remove this rule:
    img { 
      width: 584px; 
      height: 389px;
    }
  4. In its place, add the following line:
    #retina img { image-size: responsive; }
  5. Save the file, then copy it to the src folder underneath our project area (not within the Tutorial folder!).
  6. For this exercise, we're going to replace the Gulp task file—go ahead and add this code to a new file, saving it as gulpfile.js at the root of our project area:
    var gulp = require('gulp');
    var postcss = require('gulp-postcss');
    var responsiveimages = require('postcss-responsive-images');
    
    gulp.task('default', function() {
        return gulp.src('src/*.css')
        .pipe(postcss([ responsiveimages ]))
        .pipe(gulp.dest('dest/'));
    });
    
    var watcher = gulp.watch('src/*.css', ['default']);
    watcher.on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

    Note that we're concentrating on just making our image responsive with this gulp file, hence why it is a lot shorter than previous versions we have used to date.

  7. Fire up a Node.js command prompt, then change the working directory to our project area—at the prompt, enter gulp then press Enter.
  8. Node will go away and compile our code—if all is well, the compiled code for #retina img will look like this:
    Implementing responsive capabilities to images
  9. Copy the compiled CSS file from the dest folder into the css folder of the Tutorial13 folder.
  10. Go ahead and preview the results—try resizing the browser; if all is well, the image will automatically resize the image for us.

Although it's easy enough to install and use this plugin, it works best when referencing images directly in our HTML code, and not through the use of background: or content: url(…) attributes in our CSS.

What does this mean for us? It's a little limiting, as the purists amongst us may prefer to hive off asset attributes to CSS style sheets such is open source software, though this is one limitation that is bound to be fixed in the fullness of time!

The keen-eyed amongst you will spot that the image presentation clearly needs further work—for example, the paper clip isn't repositioning when the window is resized, and we need to set a minimum width so that there is some white space around the image when we resize it:

Implementing responsive capabilities to images

The key principles remain the same though, irrespective of the presentation, removing the fixed image sizes and replacing with a max-width of 100% is a good step to making an image responsive.

To get a true responsive image though, we ideally would use the new HTML5 <picture> tags—trouble is, PostCSS doesn't yet have a plugin to implement these tags!

Note

If you're interested in some of the more general techniques of making images responsive (and outside of the world of PostCSS), then take a look at https://jakearchibald.com/2015/anatomy-of-responsive-images/.

In the absence of any available capability to handle the use of <picture> tags within PostCSS, we can instead take a more traditional route and use media queries to help switch between different images, depending on the available screen estate.

We can go a step further, and even switch in images of better resolution if the device supports it—I'm thinking of course of Apple iPads or iPhones, which support retina images. We can easily use this format when working with PostCSS; for this, we need to make use of the postcss-at2x plugin by Simon Smith, available at https://github.com/simonsmith/postcss-at2x. I feel a couple of demos coming on, so without further ado, let's go explore using this plugin.

Adding support for retina images

Retina images, a term coined by Apple's marketing team, contain up to twice as many pixels in the same space as standard images. This allow us to switch in images of higher quality (or resolution) automatically, provided we're using a device that supports their use.

This might be as simple as an iPhone, or something more substantial like an iPad—Apple's marketing clout means that they are probably two of the most popular portable devices that people own! But I digress…

At a technical level, we have two routes available for adding retina images, before we explore these in more detail, let's just remind ourselves of the basics:

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { 
  #retina img {
    content: url("../img/mothorchid@2x.png");
  } 
}

This code is an extract from the CSS style sheet in the Tutorial15 folder, which is available in the code download that accompanies this book; try previewing index.html in a browser.

Tip

For best results, it is strongly recommended that you use Google Chrome—it's a great browser for simulating the effects of switching between low and high resolution images.

The image displayed displays the text 8-bit version—to switch, try this:

  1. Press Shift + Ctrl + I to display the Developer toolbar.
  2. Click on the mobile phone icon to enable Responsive Design mode
    Adding support for retina images

We can then switch between different devices using the dropdown—try switching to Apple iPad; you may need to press F5 to refresh the display. If all is well, it will switch between 8-bit and 24-bit versions of the orchid image.

Taking the next steps

This is all good, but we're clearly not using PostCSS here—what are our options? Well, we have two that we can use: customMedia() or the postcss-at2x plugin. We've already covered the basics of using customMedia in the Exploring custom media queries in PostCSS section; for this, we would use a variable such as this:

/* media query for hi-resolution image support */
@custom-media --hi-resolution screen and (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi);

This would be coupled with a query such as this:

@media (--hi-resolution) { 
  #retina img {
    content: url("../img/mothorchid@2x.png");
  } 
}

When compiled, and run in Google Chrome (to take advantage of its responsive design tools), we can see the image switch from 8-bit:

Taking the next steps

…to a 24-bit version of the image:

Taking the next steps

A peek at the active style rules view shows the media query update automatically:

Taking the next steps

This is good, but still a manual approach that takes time—instead, we can use a quicker route to achieve similar results. The alternative route, using postcss-at2x, is a simpler option—instead of working out what resolution ratio to use, we simply add the term at-2x to our style rule:

#retina img { background: url("../img/mothorchid.png") at-2x; }

This automatically compiles to produce the relative resolution statements for us in our style sheet. It's a useful trick to use when working with iPads and other devices that can support hi-res images.

Tip

Make sure the src and dest folders at the root of our project area are clear of files before starting this demo, otherwise you might find they have some undesired effects during compilation!

Let's dive in and take a look at this in more detail.

  1. We start, as usual by installing the plugin—fire up a Node.js command prompt, then change the working directory to our project area.
  2. At the prompt, enter the commands shown in this screenshot, pressing Enter after each:
    Taking the next steps

    Keep the window handy, we will need it in a few steps!

  3. Let's now set up our markup, extract a copy of the Tutorial17 folder from the code download that accompanies this book, and save the folder to our project area.
  4. Extract a copy of the gulp file from this folder and use it to replace the existing one at the root of our project area.
  5. Extract a copy of style – pre-compile.css from the Tutorial17 folder, then copy it to the src folder at the root of our project area. Rename it as style.css.
  6. Switch back to the Node.js command prompt window we had up earlier—at the prompt, enter gulp then press Enter.
  7. PostCSS will go away and compile our code—if all is well, we should see something akin to this extract in the compiled file within the dest folder:
    #retina img {
      padding: 4px;
      border: solid 1px #bbb;
      background: #fff;
      box-shadow: 0 1px 2px rgba(0,0,0,.2);
      content: url("../img/mothorchid.png"); 
    }
    …
    @media screen and (-webkit-min-device-pixel-ratio: 2), (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { 
      #retina img {
        content: url("../img/mothorchid@2x.png");
      } 
    }
  8. Go ahead and copy the contents of the dest folder to the css folder within the Tutorial17 folder.
  9. Try previewing the demo—if all is well, we should see that orchid flower as before, and force Chrome to display the hi-res version as we did in our previous demo.

The great thing about this plugin is that it deals with creating the media query for us; all we need to do is add the at2x tag to any image where we want to display hi-resolution versions in the browser. There is always a risk that we may end up producing queries that are not 100% optimized (for example, combining identical breakpoints into one block, and so on); we will explore a couple of options to help keep our queries working efficiently towards the end of this chapter.

As an aside, a more concise option for working with hi-res images which is frequently forgotten, is the use of image-set(); this performs in a similar fashion, by providing different versions for devices that support high-resolution images. PostCSS provides a fallback option in the form of postcss-image-set (available from https://github.com/alex499/postcss-image-set), which sets a basic image that will work in those browsers that don't support the use of image- set() within a style sheet.

Exploring other media possibilities

So, we've covered a number of key topics around making content responsive, using media queries; what does this mean when using PostCSS? The simple answer is that it opens up a world of possibilities—if your site needs to use media queries, then it is very likely that we can use PostCSS to compile our queries into valid CSS rules. To pique your interest, here are a couple of options to consider:

  • Creating a responsive slider using the bxSlider plugin, available from http://www.bxslider.com. Granted, it uses jQuery to move between each slide, but who's to say you couldn't eventually convert this to an all-CSS option?
  • How about using responsive image sprites? A classic use for this is credit card symbols on an e-commerce shopping cart, with a bit of care, we can even make the image adapt to display hi-res versions, if the device being used supports it. We'll cover more of this in Chapter 5, Managing Colors, Images and Fonts, if you want to give this a try, take a look at the postcss-sprites plugin, available from https://github.com/2createStudio/postcss-sprites.

Okay, we've covered making images responsive using PostCSS, but what about text? Pages won't look good if text doesn't flow properly when content is resized. Thankfully we can apply similar principles to text, using the postcss-responsive-type plugin by Sean King—let's take a look at it in action.