38,39 €
Explore the power of PostCSS to write highly performing, modular, and modern CSS code for your web pages
This book is ideal for web developers and designers who are comfortable with HTML5 and CSS and now want to master PostCSS for web design. Web designers who have been using SASS or Less and now want to adopt PostCSS would also find this book useful.
PostCSS is a tool that has quickly emerged as the future of existing preprocessors such as SASS and Less, mainly because of its power, speed, and ease of use. This comprehensive guide offers in-depth guidance on incorporating cutting-edge styles into your web page and at the same time maintaining the performance and maintainability of your code.
The book will show how you can take advantage of PostCSS to simplify the entire process of stylesheet authoring. It covers various techniques to add dynamic and modern styling features to your web pages. As the book progresses, you will learn how to make CSS code more maintainable by taking advantage of the modular architecture of PostCSS. By the end of this book, you would have mastered the art of adding modern CSS effects to web pages by authoring high performing, maintainable stylesheets.
This comprehensive book provides in-depth guidance on how to build a PostCSS powered responsive site from scratch. Following a step-by-step approach, you will learn how to add modern styles to web pages. It also contains several tips and best practices on how you can optimize your sites by writing high performing code in PostCSS.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 540
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2016
Production reference: 1240616
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-589-1
www.packtpub.com
Author
Alex Libby
Reviewer
Michael Ebbage
Commissioning Editor
Wilson D'souza
Acquisition Editor
Larissa Pinto
Content Development Editor
Riddhi Tuljapurkar
Technical Editors
Chinmay Puranik
Jayesh Sonawane
Copy Editor
Safis Editing
Project Coordinator
Sanchita Mandal
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
Alex Libby's background is in IT support—he has been involved in supporting end users for almost 20 years in a variety of different environments; a recent change in role now sees Alex working as an MVT test developer for a global distributor based in the UK. Although Alex gets to play with different technologies in his day job, his first true love has always been the open source movement, and in particular, experimenting with CSS/CSS3, jQuery, and HTML5. To date, Alex has written 10 books on subjects such as jQuery, HTML5 video, SASS, and CSS for Packt and has reviewed several more—Mastering PostCSS Web Design is Alex's eleventh book for Packt.
I would like to thank my family and friends for their support throughout the process and the reviewers for their valued comments; this book wouldn't be what it is without them! I would also particularly like to thank Andrey Sitnik for his work in producing PostCSS and being really helpful and patient in answering questions about some of its more complex parts. My grateful thanks also to Ernie Salazar from NPM, who helped with issues with publishing the plugins created for this book, and David Clark for his assistance with getting me back on track with the postcss-bem-linter plugin, also used in the book. Thank you all—I couldn't have finished the book without your help!
Michael Ebbage is a software architect who specializes in e-commerce and Java technology-based web applications. He created his first web page almost two decades ago—since then, he's gone on to develop hundreds of websites for some of the UK's biggest companies (many featuring on the FTSE 100 and 250), as the tools and techniques used to do so have continually changed and evolved.
He has a background in software development and holds a BSc (Hons) in computing and information systems. He is also one of the top contributors to Stack Overflow, where you'll regularly find him answering questions on a wide range of web-related languages and technologies.
I'd like to thank the author, Alex, for the opportunity to be involved with this book. It's been a great learning experience, and I now have a renewed admiration for the amount of knowledge and effort that goes into it. I would also like to thank my beloved wife and son for their patience and support during the time I spent working on reviewing it.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
As a developer, I'll bet you have a perfect workflow—you either write styles using plain vanilla CSS or use one of the current processors, such as SASS or Less, to create them. You'll add vendor prefixes using the likes of Autoprefixer—either manually or using a tool, such as Grunt or Gulp.
Sounds familiar? Why would you want to disturb something if it works for you, right?
Trouble is, a friend or colleague has started talking about a new processor by the name of PostCSS—they've piqued your interest sufficiently to want to find out more about what it is and how it works.
Well, welcome to the fast-growing ecosystem that is PostCSS! By itself, the tool doesn't do anything, but when paired with the right plugins (and there are hundreds available for use), it has the potential to become a really powerful processor for you. Gone are the days when we have to depend on a monolithic library such as SASS or less. Instead, we can pick and choose exactly which plugins to use based on our project requirements. PostCSS is an immensely quick processor to use; the question is, are you ready for the ride?
Here's hoping the answer is yes; if so, let's make a start.
Chapter 1, Introducing PostCSS, kicks off our journey with an introduction to the world of PostCSS, exploring its features and how we can use this ecosystem to transform basic code into valid CSS styles that we can use within our projects. You will discover the benefits of using this ecosystem and how its architecture and modular approach allows us to put together a processor that is tailored specifically for our needs.
Chapter 2, Creating Variables and Mixins, takes a look at some of the basic concepts that are familiar to users of existing processor technologies, such as variables and mixins. You will learn how to transition them to PostCSS and discover how the benefits of using these techniques can transition through to using PostCSS.
Chapter 3, Nesting Rules, explores how existing processors, such as SASS or less, take advantage of concepts such as nesting to reduce the amount of code we need to write and how we can replicate the same functionality within our PostCSS processor.
Chapter 4, Building Media Queries, walks us through the basics of adding responsive support to websites using PostCSS and media queries. You'll learn how to retrofit support for older websites and browsers, and explore how we can take things further with the advent of CSS4 media queries and provide support today within PostCSS.
Chapter 5, Managing Colors, Images, and Fonts, examines the plugins available for handling and manipulating images, colors, and fonts within PostCSS. We will work through a number of examples to illustrate how both images and colors can be manipulated within PostCSS, such as creating image sprites or altering colors using palettes within the system.
Chapter 6, Creating Grids, takes us on a journey through constructing the skeleton of a website using grids—we will explore the basic concept behind using grids and discover some of the plugin options available for creating them within PostCSS. We will work through some examples using the Bourbon Neat grid system, before replicating the examples with PostCSS-equivalent plugins and adding responsive capabilities to the resulting code.
Chapter 7, Animating Elements, begins with a quick recap of using JavaScript to animate content, before switching to using CSS for animation, and how you can transition through to using PostCSS. We will explore using some of the more well-known libraries, such as Animate.css, before creating a quick demo using PostCSS and learning how to optimize our animations using PostCSS.
Chapter 8, Creating PostCSS Plugins, teaches us how plugins can be used to extend PostCSS, and takes us through a journey of exploring the typical architecture of such a plugin. You will then take a look at some example plugins before working through creating your own plugins using the boilerplate code available and before testing and making the plugins available for download by users from the Internet.
Chapter 9, Working with Shortcuts, Fallbacks, and Packs, starts by examining some of the shortcut plugins and packs available before exploring how we can supplement them with creating our own shortcut plugins. You will also discover how you can lint and optimize your code using one of the plugin packs available for PostCSS and learn how to provide fall-backs to PostCSS code to help maintain support for older browsers.
Chapter 10, Building a Custom Processor, pulls together some of the techniques we've covered thus far in the book to produce a custom processor that we can use as a basis for transforming code in our projects. You will explore how to optimize the output before adding source map and vendor prefix support and then testing it on a website. You will then round off the chapter with a look at extending the processor to use the CSStyle framework to allow you to write code that works for both SASS or PostCSS.
Chapter 11, Manipulating Custom Syntaxes, introduces us to writing custom syntaxes using the API and explores some of the options available for parsing code written using syntaxes such as SASS or less. We work though some examples of parsing code using PostCSS before converting the output into something that can be displayed on screen or saved to a file. We will also add in support for highlighting our code using the midas library.
Chapter 12, Mixing Preprocessors, shows us how we can begin to mix processors as an aid to make the transition to using PostCSS. We will take a look at the Pleeease library before installing it and using some of its features. We will then set up a compilation process before using it to make changes to a standard WordPress theme.
Chapter 13, Troubleshooting PostCSS Issues, takes a look at some of the more common issues we might experience when using PostCSS, such as the "taskname not in our gulpfile" error. We will also take a look at what to do next if all else fails. We will cover the methods for getting help with an issue or logging details of a bug within either the core PostCSS system or one of its plugins.
Chapter 14, Preparing for the Future, covers some of the possible options for supporting future style standards from what people know as CSS4. You will also explore some of the risks involved and how you can replicate support using existing plugins available today or extend them to increase support for new CSS4 selectors.
All you need to work through most of the examples in this book is a simple text or code editor, a copy of NodeJS (for your platform), Internet access, and a browser. I recommend installing Sublime Text 3; it works well with Node and Gulp, which we will use throughout the book.
Some of the examples make use of additional plugins; most (if not all) can be installed directly from within NodeJS. Details are included within the appropriate chapter along with links to view the plugin source code and documentation.
The book is for frontend developers who are familiar with HTML5 and CSS3, but want to master PostCSS as part of simplifying their development workflow or remove the dependency on existing processors, such as SASS or Stylus. To get the most out of this book, you should have a good knowledge of HTML, CSS3, and JavaScript, and ideally, have some experience of using preprocessors such as SASS, Less, or Stylus.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-PostCSS-for-Web-Design. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/MasteringPostCSSForWebDesign_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
A key part of any website is styling—it doesn't matter if this is for a simple element tag or a complex animation; a website is not a website without color and action. Building styles for any online presence takes time and effort—we can reduce development time by using a preprocessor to automate the creation of styles, automatically apply vendor prefixes and the like, but the extra dependency of a library can be like using a sledgehammer to crack a nut!
Enter PostCSS—its unique modular style allows us to create a leaner, faster CSS processor, with no external dependencies. In this chapter, we look at installing PostCSS, understanding its architecture, and learn how to use its speed and power to compile code into valid CSS. We will cover a number of topics throughout this chapter, which will include the following:
Let's make a start…!
All of the exercises in this book are written for the Windows platform; please adjust accordingly if you use a different operating system.
A question: what do SASS, Stylus, Haml, and Less all have in common?
The answer is, they are all compilers, source to source compiling, or transpilers (to give them their official name), that have been around since the 1980s. They have appeared in many different formats, with Digital Research's XLT86 being one of the earliest versions, dating from 1981.
More recently, the well-known SASS processor arrived in 2006; this was followed by Less, created by Alexis Sellier in 2009. Both work in a similar fashion: they take a set of rules and compile it into valid CSS. We can extend CSS with all manner of features, such as variables, mixins, functions, and more. Although processors may not help cut down the physical number of lines we have to write, they help us reorganize code into more manageable blocks that we can reuse in future projects, which helps make CSS easier to maintain.
But, as is nearly always the case, there are some drawbacks to using processors:
Hmm, this doesn't make processing so attractive! But what if there were a way to alleviate all of these issues, and remove the need for dependencies at the same time?
Well, there is: let's build our own processor! Okay, this might sound a little crazy, but as someone once said, there is method in this madness, so bear with me while I explain why this may be a better option.
At the beginning of this chapter, I mentioned that we would focus on creating our own preprocessor, right? Well, I have a little confession to make: we're not. Hold on, what gives?
Well, we will create a preprocessor…but we will also create a postprocessor too. Let me explain why—our alternative "option" allows us to create both at the same time. Our alternative option is PostCSS, which can be downloaded from https://github.com/postcss/postcss. PostCSS is used by some major companies, such as Twitter, Google, Bootstrap and CodePen, and even WordPress (in a limited capacity).
PostCSS was built as a Node.js module, so will work with any number of the existing plugins already available for Node.js—we will be using a number of these plugins throughout the book. Let's take a moment to explore some of the benefits of this tool.
What do we mean by PostCSS? In a nutshell, it can be used to refer to one of two things—the PostCSS core tool or the plugin ecosystem that is powered by the tool. On its own, it doesn't actually do a lot; once we start adding plugins, we can achieve a great deal. Let's explore what this means in practice:
Well, there are some considerations to using a custom processor; the key thing to remember is that PostCSS is neither a pre- nor post-processor, but more of a Swiss Army Knife of a toolbox that we can use to process our CSS code. Let's take a look at some of these drawbacks:
You already develop sites using a preprocessor such as SASS. You can compile code using a standalone processor, but normally prefer to use Node.js and Gulp to complete the task. Sound about right? What about making the move to using PostCSS?
No problem, we can include a section for processing CSS files using PostCSS. The key here is to not use PostCSS to perform the initial compilation, but to perform the post-processing, such as adding vendor prefixes or minifying the results. Once this is established, we can start to incorporate some of the plugins available for PostCSS that allow us to replicate functionality, such as from within SASS. Once we've adjusted existing code to use the format required by the plugins, we can then switch to using PostCSS, and begin to remove our dependency on using SASS.
At this point, it is worth spending a few minutes to help clear up some common misconceptions about PostCSS, although many associate it as being a preprocessor, or even a postprocessor, this isn't what was intended:
Okay, let's move on, I think it's time for less chat and more action, right? Let's get stuck in to producing something; there's no better time than now to get PostCSS installed and ready for use.
Before we do so, we just need to cover a couple of requirements. First, we need to set up a local web server. It's not critical, but gives a better effect. I personally use WAMP Server (for PC, from http://www.wampserver.com/en), otherwise, Mac users can try MAMP (http://www.mamp.info/en), or the cross-platform Apache web server (from http://www.apachefriends.org). In each case, default settings should be sufficient.
The second requirement is to set up a project area; assuming you have set up a WAMP as a local web server, go ahead and set up a folder called postcss in c:\wamp\www, as shown in this screenshot:
Right, with that out of the way, let's make a start on getting PostCSS installed!
The first step on our journey is to get PostCSS installed—this runs from Node.js; we can use any one of several task runner plugins to install it. For the purpose of the exercises throughout this book, we will use Gulp; if you prefer, alternatives such as Grunt or Broccoli can be used.
When using Node.js, make sure you use the Node.js command prompt, and not node.exe; the exercises will not work when using the latter!
Let's make a start with installing Node and Gulp:
When installing, accept all defaults; this will be sufficient for the exercises throughout this book.
Next, bring up a Node.js command prompt, enter the following command, and press Enter:The output shown is the version of Node that is installed; this is a quick check to ensure Node.js has indeed been installed correctly:
Now that Node is installed, we need to create a package.json file to store our dependencies for projects. Run this command at the command prompt, and press Enter:We now have Node configured and an empty package.json file in place, so let's add our dependencies. We will start by adding Gulp first:
Once completed, Gulp is now ready for use; we can go ahead and install PostCSS.
A small point on the use of --save-dev: this installs any dependencies required to develop using a specific plugin; if we simply need the dependencies for running the plugin (in a production environment), then we can simply use --save instead.
We're at the interesting stage now—installing PostCSS. PostCSS is available from https://github.com/postcss/postcss, and can be installed into Node using a Gulp plugin. Let's do that now:
If all is well, we should see something akin to this screenshot:
On its own, PostCSS doesn't do anything; to make it more useful, we are going to install three plugins. We will explore using plugins in greater detail later in the book, but for now, don't worry too much about what is happening:
To make it easier to view JSON files in Sublime Text, try installing and activating a custom theme, such as MonokaiJSON Plus, available to install from https://github.com/ColibriApps/MonokaiJsonPlus.
PostCSS is now installed for use, but if we try to use it, we probably won't get very far, as it needs to be configured for use! Let's take a look at doing that now, by creating a simple example that will add vendor prefixes to some sample CSS rules, and automatically minify the results.
So far, we've covered the basics of setting up and using PostCSS. It's worth taking a moment to learn about how it works, to better understand how we can use it and develop our own plugins for the platform.
PostCSS is like me on a Saturday morning after a good night out: it does nothing! Yes, it's true, by itself, the application doesn't do anything at all; it's when we add plugins into the mix that it starts to become useful.
The key to PostCSS is treating it as an enabler, it is not meant as a direct replacement for your existing preprocessor, or even postprocessor, but to complement them. It works on the basis of parsing code, processing it with any assigned plugins, and rendering the results:
It works by parsing content into an Abstract Syntax Tree (or AST) with a series of nodes. Each node in the tree contains a symbolic representation of an element in your code. In other words, if you had a condition statement that pointed to three possible outcomes, then the AST would have a single node, with three branches representing the possible outcomes.
For an example of an AST, take a look at http://jointjs.com/demos/javascript-ast, which shows the breakdown of a simple arithmetic function using plain JavaScript.
Our AST is then sent through one or more plugins (we must always use one plugin, but can have many in our gulp file). It then converts the code to a long string, before processing it through any assigned plugins and spitting out the result in the form of valid CSS. We can use this as a basis for creating our own plugins, using the boilerplate code and API that are both available from the main PostCSS site on GitHub.
The trick to the plugin stage is in the mix of plugins we must use to satisfy our needs; the better ones should only perform one role. Any that perform multiple tasks are less ideal, as they are likely to contain excess functionality that we don't need in our projects.
Assuming we decided to use PostCSS, there is almost always one question at the top of everyone's mind: how do we make the move?
In short, the key here is not to simply assume existing code can be put through the PostCSS process, as it will likely not work. Instead, we should take an iterative process, and begin to convert low-hanging fruit to using PostCSS. The process will of course require some work, but there are tips on how we can reduce the pain involved in making the switch to PostCSS.
The key to making the transfer is to work out what functionality needs to be processed, then to create the initial framework for a build process (for example, a Gulp or Grunt task file), then to gradually add in plugin support one by one, until you have a fully working compiler.
We can take this a step further, and use plugins that replicate SASS code format into PostCSS; an ideal plugin to start with is Autoprefixer, followed by plugins such as postcss-mixins or postcss-partial-import. We will explore using SASS as a basis for a custom syntax in Chapter 11, Manipulating Custom Syntaxes, where we will use these two plugins, and more, to help make the transition process easier and help remove the dependencies on preprocessors such as SASS or Less. Oh, and above all, being based on JavaScript makes it portable; what more could a developer ask for, I wonder?
Many of the SASS format plugins for PostCSS now come in the PreCSS pack. We will explore using this in Chapter 10, Building a Custom Preprocessor.
Okay, on we go. Over the course of the next few chapters, we will take a look at different processor elements that are commonly used to create build processors, such as variables or mixins. We'll see how they might typically be written in processors such as SASS or Less, then work on converting our code to use PostCSS equivalents before processing to produce valid CSS. We will then finish up with pulling everything together to build your own custom processor for use in future projects.
Writing valid CSS is an art that has been present since the dawn of the Internet; this takes skill, patience, and time to produce and perfect any masterpiece. Processors such as SASS or Less have helped to make the process more efficient, but are not without their drawbacks; PostCSS allows for a more customized approach, but without the extra baggage. We've covered a few key points around PostCSS throughout this chapter, so let's take a moment to review what we've learned.
We began with a brief look at the art of processing, before introducing PostCSS as a tool. We then explored some of the benefits and drawbacks of using it, and how it can fit in seamlessly with your existing development workflow, with a little careful planning.
Next up, we covered the installation of PostCSS along with Gulp as the task runner/host process, before embarking on a simple demo to introduce how the compilation process works, and that with the right choice of plugins, we can take out some of the manual grunt work required to manage our code (pun intended!). With our code compiling, we then turned our attention to adding a watch facility, and automatic support for linting our code, to ensure we maintain consistent standards.
We then rounded out the chapter with a look at how PostCSS works, and understanding something of its architecture, so that we can begin to make the move from using plain CSS or an existing preprocessor, to using PostCSS.
Phew, we've certainly covered a lot; it's time to really get stuck in now, and start to use PostCSS in earnest. Over the next few chapters, we will explore a number of different concepts that are common to existing preprocessors, and explore how we can benefit from making the transition to using PostCSS. We have to start somewhere, so we'll kick off with using variables, functions, and mixins in the next chapter, and see how we can use some of the techniques from processors, but without the associated baggage!
A question: how often have you created components such as buttons, where you've used very similar colors multiple times throughout your code? It's a real pain to manually alter. Using a preprocessor such as SASS or Less makes it easier, but with the overhead of a full-sized library.
Can we do it differently? Absolutely; throughout the next few chapters, we'll explore different elements of PostCSS, before pulling it all together to produce a preprocessor application later in the book. We'll begin our journey with a look at using variables and mixins; we'll explore the basics of creating them first, before transitioning to support using PostCSS. In this chapter, we'll cover the following topics:
Let's get cracking!
So far, we've covered the basics of installing and configuring PostCSS—although there are a few steps involved, it's an easy process to get started with using the processor. To really get to know it though, there is no substitute for using it in anger; it's amazing how much you can automate, with just a little care and planning!
Let's put that to the test and use it to create a couple of simple examples using variables, functions, and mixins. We'll start with creating the original version using SASS, before converting it to use PostCSS plugins. The demos do assume a level of prior knowledge around using SASS, so if you are at all unfamiliar, then you may like to refer to my book,