12 Using preprocessors

 

This chapter covers

  • CSS preprocessors
  • Examples of how Sass extends CSS functionality

So far in this book we have been writing all our styles using plain CSS. However, we can also use pre-processors. Each has their own syntax and most extend the currently existing CSS functionality. The most commonly used preprocessors are:

They were created to facilitate writing code that is easier to read and maintain as well as for added functionality not available in CSS alone. Styles written for use with pre-processors have their own syntax and then must be built or compiled into CSS. Although some provide ways for browser-side compilation the most common implementation is to pre-process the styles and serve the output CSS to the browser[1].

The benefit of using a pre-processor is in the added functionality it brings examples of which will be covered in this chapter. The drawback is that we now need a build step for our code. Which preprocessor to choose is a personal choice based on what functionality is needed for the project, team knowledge, and, if using a framework, which ones are supported. For our project, we are going to choose based on popularity. When developers were surveyed about their sentiments regarding CSS preprocessors, the majority of respondents seemed to favor Sass (figure 12.1) so that is what we are going to use.

Figure 12.1 pre-processor sentiment[2]

12.1 Running the pre-processor

12.1.1 Setup instructions using npm

12.1.2 .sass versus .scss

12.1.3 Setup instructions using CodePen

12.1.4 Starting HTML and SCSS

12.2 Sass Variables

12.3 @extend

12.4 @mixins and @include

12.4.1 Object-fit

12.4.2 Interpolation

12.4.3 Using the mixin

12.4.4 border-radius shorthand

12.5 Nesting

12.6 @each

12.7 Color functions

12.8 @If / @else

12.9 Final Thoughts

12.10 Summary

sitemap