Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Sass and Compass Designer's Cookbook
Sass and Compass Designer's Cookbook

Sass and Compass Designer's Cookbook: Over 120 practical and easy-to-understand recipes that explain how to use Sass and Compass to write efficient, maintainable, and reusable CSS code for your web development projects

eBook
₹799 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Sass and Compass Designer's Cookbook

Chapter 1. Getting Started with Sass

In this chapter, you will learn how to do the following:

  • Installing Sass for command line usage
  • Installing Compass
  • Using Sass on the command line
  • Using the Sass interactive mode and SassScript
  • Using the sass-gulp plugin with Gulp
  • Using Sass in the browsers
  • Writing Sass or SCSS
  • Choosing your output style
  • Working with partials
  • Writing your code in a text editor

Introduction

This chapter guides you through the installation of Sass and explains the different ways you can compile your Sass code into static CSS. You will not only learn how to use Sass using the command line interface (CLI), but you will also be introduced to LibSass. LibSass is a C/C++ port of the Sass engine.

Based on LibSass, sass.js is a pure JavaScript implementation of the Sass engine, which enables you to compile Sass code with JavaScript and run sass.js in your browser.

The sass-node is an interpreter of LibSass for Node.js, and it enables you to compile Sass in a Node.js environment. Together with a task runner, such as Gulp or Grunt, you can use the sass-node to set up a build chain for your projects.

In this book, the SCSS syntax for Sass has been used in favor of the original indented Sass, that is, the Ruby-like syntax. You can write your SCSS code in your favorite text editor, but at the end of this chapter, you will also be introduced to some Graphical User Interfaces (GUI) that will help you write and compile your code more easily.

Installing Sass for command line usage

In this recipe, you will learn how to use Sass on the command line.

Getting ready

You can install Sass on Linux, Mac, and Windows. Sass has been written in Ruby. So, installing Sass requires that you install Ruby first. Ruby is a dynamic open source programming language with its focus on simplicity and productivity. You can read more about Ruby in the Ruby and MongoDB Web Development Beginner's Guide book by Gautam Rege. You will find this book at https://www.packtpub.com/web-development/ruby-and-mongodb-web-development-beginners-guide. If you are using Mac, you are lucky because OS X has Ruby preinstalled. Linux users should use a packages manager, such as Advanced Package Tool (APT), to install Ruby:

 sudo apt-get install ruby-full

Other methods to install Ruby on Linux can be found at https://www.ruby-lang.org/en/documentation/installation/.

Finally, if you are on Windows, RubyInstaller is available. RubyInstaller is a single-click installer that includes the Ruby language, an execution environment, important documentations, and more. You can find RubyInstaller at http://rubyinstaller.org/.

How to do it...

After installing Ruby, you can use the following steps to install Sass on your system:

  1. Open a terminal or a command prompt. Mac users should run Terminal.app and Window users can use the cmd command.
  2. Then, enter the following command in your console:
    gem install sass
    

    The preceding command requires administrator rights for some systems. Use the sudo command for global installations with administrator rights.

  3. Now, you should be able to check your installation by running a command, such as the following one:
     sass -version
    
  4. The preceding command should generate the following output:
    Sass 3.4.13 (Selective Steve)
    

How it works...

RubyGems is Ruby's package manager. Ruby packages, called gems, can easily be installed via the command line and be distributed over the Internet. Many gems are hosted at https://rubygems.org/ and https://github.com/. Also, Sass is distributed as a gem. The Sass gem will not only install Sass, but also install all the dependencies for you. Installing Sass with RubyGems will be easy and straightforward.

The gem install sass command in this recipe should install Ruby Sass and all its dependencies.

There's more...

After installing Sass, you can use the --help option to get a list of the available options and a short instruction on how to use the command-line compiler:

sass --h+elp

Besides the Sass compiler tool, the Ruby Sass gem also installs the sass-convert command-line tool. The sass-convert tool can be used to convert files from the indented syntax into the newer SCSS syntax and vice versa. Notice that you can also use sass-convert to migrate the CSS code Sass or the SCSS code. This will give you some basic nesting when migrating your CSS code.

In the Writing Sass or SCSS recipe of this chapter, you can read about the differences between the original indented syntax and the newer SCSS syntax.

The Ruby on rails apps can also use the Ruby Sass gem to compile the CSS code. Read more about Ruby on rails and Sass in Chapter 14, Ruby on Rails and Sass, of this book.

See also

Installing Compass

Compass is an open source framework for Sass. Compass helps you write reusable CSS3 code with Sass by using reusable patterns. In this recipe, you will learn how to install Compass for command-line usage. Compass can easily be extended, and it ships with handy features, such as mixins for creating typographic rhythms and image sprites. Finally, Compass can also help you prefix your properties to handle browser compatibility. Read more about vendor prefixes in the Using vendor prefixes recipe of Chapter 7, Cross-Browser CSS3 Mixins. You can read more about Compass and its features further on in this book and especially in Chapter 6, Using Compass.

Getting ready

You will have to install Ruby before installing Compass. In the Installing Sass for command line usage recipe of this chapter, you can read how to install Ruby on your system. Both Compass and Ruby run on Linux, OS X, and Windows. When you install Compass before you have installed Sass, Sass will be installed automatically, since Ruby Sass is a dependency of Compass.

How to do it...

After installing Ruby, you simply have to run the following command in your console to install Compass:

gem install compass

That's all. You can also try the following steps to get a short impression of how to run Compass on the command line:

  1. Create a new compass project with the following command:
    compass create project
    
  2. The preceding command will create a new folder called project, which will contain the files shown in this image:
    How to do it...
  3. Now, you can compile your project by running the following command:
    compass compile project
    

How it works...

The config.rb file contains the configuration for your Compass project. This file is well-commented, and it contains, among others, the path to your project's folders.

Running the compile project command compiles each Sass file from the Sass (sass_dir) folder into a CSS file in the stylesheets (css_dir) folder. Files having a name starting with an underscore (_) are called partials and are not compiled into a CSS file. You can read more about partials and how to use them in the Working with partials recipe of this chapter.

There's more...

You can also directly use the features, mixins, and helper functions of Compass together with the command-line Sass compiler (see the Using Sass on the command line recipe of this chapter) by setting the --compass option. For more information on integrating compass in your compile process, you can read Chapter 6, Using Compass.

Compass is a widely used Sass framework. Many other frameworks for Sass are available too. Susy is a powerful set of Sass mixins for building grid-based layouts. Susy was originally built to be a part of the Compass ecosystem. In Chapter 9, Building grid-based layouts with Sass, and Chapter 10, Susy and Sass, of this book, you can read about Susy. And in Chapter 13, Meeting the Bourbon Family, of this book you will be acquainted with Bourbon. Bourbon is another library of Sass mixins.

This recipe demonstrates how to set up a project with only Compass. In the Adding Compass to an existing Sass project recipe of Chapter 6, Using Compass, you can read how to integrate Compass into existing projects too.

See also

The official website for the Compass framework can be found at http://compass-style.org/.

Using Sass on the command line

You can run Sass on the command line to compile your Sass files directly into the CSS code.

Getting ready

In the Installing Sass for command line usage recipe of this chapter, you have already read how to install Sass. Linux users have to open a terminal, while Mac users have to run the Terminal.app, and Window users have to use the cmd command for command-line usage.

How to do it...

Use the following steps to find out how to compile your Sass code in the command line:

  1. Create a Sass template called first.scss that contains the following SCSS code:
    $color: orange;
    
    p {
      color: $color;
    }
  2. Then, run the following command in your console:
    sass first.scss
  3. You will find that the preceding command outputs the CSS code as it is shown here:
    p {
      color: orange; }

How it works...

Firstly, notice that the example code in this recipe uses the newer SCSS syntax for Sass. In the Writing Sass or SCSS recipe of this chapter, you can read why this book uses the SCSS syntax in favor of the original indented Sass syntax.

The sass command directly outputs the compiled CSS code to your console. To save the output in a file, you will have to set a second output argument, as follows:

sass first.scss first.css

The preceding command creates a new first.css CSS file that contains the compiled CSS code.

There's more...

When compiling your Sass templates into CSS files, Sass does not only create CSS files, but also a folder called .sass-cache. By default, Sass caches compile templates and partials. In the Working with partials recipe of this chapter, you can read what partials are. Caching of the compiled templates and partials makes recompiling after your changes faster.

You can use the --no-cache option to disable caching.

The --compass option makes Compass imports available and loads the project's configuration. You can read more about this option in the Extending Sass with Compass helper functions and more recipe of Chapter 6, Using Compass.

Using the Sass interactive mode and SassScript

In the Using Sass on the command line recipe of this chapter, you had to create a Sass sample as an input for the Sass compiler. In this recipe, you will be introduced to the interactive Sass mode and SassScript. SassScript is a small set of extensions of the plain CSS property syntax. You can use SassScript to set property values using variables, arithmetic, and extra functions. The interactive mode enables you to enter and test your SassScript code directly in the console. SassScript can also be used to generate selectors and property names via string interpolation. You can read more about interpolation in the Interpolation of variables recipe of Chapter 3, Variables, Mixins, and Functions.

Getting ready

The interactive mode of Sass comes with the Sass gem. You can use it after installing Sass. In the Installing Sass for command line usage recipe of this chapter, you can read how to install Sass.

How to do it...

Take a look at the following steps to understand how to use the Sass interactive mode:

  1. You can start the interactive shell by running the following in your console:
    sass -interactive
    
  2. Now, you can enter the following code into the shell:
    >> 1px + 1px
    
  3. The preceding command will give the following output:
    2px
    
  4. Also, notice that you can only enter a valid code. Consider the following code:
    >> 1px + 2em
    
  5. Because Sass cannot sum different units, the preceding code will generate the following error:
    SyntaxError: Incompatible units: 'em' and 'px'.
    
  6. Also, Sass built-in function can be evaluated. Enter the following code into the shell:
    change-color(#ff0000, $alpha: 0.5)
    
  7. You will find that this returns the following output:
    rgba(255, 0, 0, 0.5)
    

How it works...

As it has already been made clear in the introduction of this recipe, you can use the interactive shell to test the property values set by SassScript. The interactive shell does not allow you to use variables or mixins, but you can make use of Sass's built-in functions. Chapter 5, Built-in Functions, of this book will introduce you to the useful built-in functions of Sass. The function used in the fourth step of this recipe is an example of a built-in function.

To quit once you have entered the interactive mode, just type Ctrl + D.

There's more...

The Compass gem has an interactive shell that is available too. You can start Compass's interactive shell by running the following command in your console:

compass interactive

In the interactive shell, you can run SassScript and you can also test the results of the Compass helper functions. Try the following command to evaluate the append-selector() helper function:

>> append-selector("p, div, span", ".bar")

The preceding command will give the following output:

"p.bar, div.bar, span.bar"

In your Sass code, you should use the preceding result inside an interpolation escape: #{ }.

Using the sass-gulp plugin with Gulp

As you know, Sass was originally written in Ruby. People wrote a port of Sass in C/C++ called LibSass, which can also be used in a development environment outside of Ruby. LibSass can easily be implemented in other languages and people have reported that LibSass is about 4,000% faster than the original Sass library (http://www.moovweb.com/blog/libsass/).

In fact, LibSass is just a library that needs an implementer. Implementers for the library can be written in any language. Implementers for C (command-line usage), Node, JavaScript, PHP, C#, and many other languages and platforms are available already.

The node-sass can be used in a Grunt/Gulp workflow. Nowadays, many developers use Grunt/Gulp workflows to compile their Sass code. This recipe will give you a short impression on how to compile Sass code with Gulp. Chapter 3, Variables, Mixins, and Functions, of this book describes the usage of Gulp to set build chains in more detail.

Getting ready

To use gulp-sass (uses node-sass), you should install Node.js (npm) and Gulp on your system first. Node.js is a platform built on Chrome's JavaScript runtime to easily build fast, scalable network applications. Gulp is a task runner or a build system written for Node.

You also have to install gulp-sass by running the following command in your console:

npm install gulp-sass

How to do it...

The following step will show you how to use Gulp and gulp-sass to compile your Sass code into CSS code:

  1. Create an example Sass file called main.scss and save this file in the sass folder. The content of this file can look as follows:
    $color: orange;
    
    p {
      color: $color;
    }
  2. Then, create your Gulpfile.js file as follows:
    var gulp = require('gulp');
    var sass = require('gulp-sass');
     
    gulp.task('sass', function () {
        gulp.src('./sass/*.scss')
            .pipe(sass())
            .pipe(gulp.dest('./css'));
    });
  3. Now, running gulp in your console will output to your console, as follows:
    [17:22:51] Using gulpfile ~/Gulpfile.js
    [17:22:51] Starting 'sass'...
    [17:22:51] Finished 'sass' after 24 ms
  4. The preceding command creates a new file called css/main.css. This CSS file contains the following CSS code now:
    p {
     color: orange; }

How it works...

The gulp-sass plugin is a plugin for Gulp that enables you to compile your Sass code with node-sass. node-sass is the node interpreter for LibSass.

As it has been already explained, Gulp is a task runner. The Gulpfile.js file defines the task. This file has been written in the JSON format.

The gulp.src ('./sass/*.scss') code reads all the files with the .scss extension from the sass folder. The content of each file is compiled with the sass() command from the gulp-sass plugin. And the compiled CSS will finally be saved in the folder set by gulp.dest().

Each SCSS file will be compiled in a new CSS file, but notice that the partial files (see the Working with partials recipe of this chapter) are ignored.

There's more...

Gulp is just like Grunt—a task runner for node. Grunt does not use streams like Gulp, but saves results directly in files. Grunt has a longer history and a big community too. On the other hand, people find streams (saving file contents in memory) more intuitive and the number of Gulp plugins grows fast. In this book, Gulp is used for setting up build chains without saying that it's better than Grunt or any other task runner. Bootstrap, as discussed in Chapter 12, Bootstrap and Sass, of this book, uses Grunt, while Foundation uses Gulp. You can read more about Foundation in Chapter 11, Foundation and Sass. You can read more about Grunt in Chapter 16, Setting up a Build Chain with Grunt, of this book.

Also, a gulp version for Ruby Sass is available at https://github.com/sindresorhus/gulp-ruby-sass. In the past, the Sass Ruby gem was leading in regards to developing new features. Because LibSass was not directly updated after the releases of Ruby Sass, there were differences between Ruby Sass and LibSass. Recently, LibSass has become part of the Sass community, and Ruby Sass and LibSass are maintained at the same speed as much as possible. Some minor differences between both the versions can be found, but Ruby Sass will usually wait for feature parity with LibSass.

See also

  • Sass Compatibility is a database that reports incompatibilities between different Sass engines. If you want to be sure about whether a feature differs between Ruby Sass and LibSass, you can look up information about the future in the database at http://sass-compatibility.github.io/. The website of Sass Compatibility will also give you the possibility of comparing different versions of the same engine.
  • Read more about Gulp at http://gulpjs.com/.
  • Read more about Grunt at http://gruntjs.com/.

Using Sass in the browsers

LibSass for JavaScript, called sass.js in short, also offers the opportunity to run the Sass compiler in browsers. In this recipe, you will learn how to run Sass in browsers with sass.js. sass.js is the only pure JavaScript implementation of LibSass, and it should generate the same output as node-sass does.

You should not use the code in this recipe for production. Besides, JavaScript files are large; you do not want every user of your website having to compile your client-side stylesheets.

Getting ready

Bower is a package manager for the web-optimized for the frontend. You can install bower by running the following command:

npm install - bower

You can run the following command to install sass.js and jQuery:

bower install sass.js jquery

After installing sass.js, you will need a text editor to edit the HTML file and a browser to inspect the results. You can also find the source code of this recipe in the downloaded files of this book.

How to do it...

Here is how you can compile Sass code in your browser:

  1. Use your favorite text editor to write down the following HTML code in a file called demo.html:
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Sass in browser</title>
        <script src="bower_components/jquery/dist/jquery.min.js"></script>
        <script src="bower_components/sass.js/dist/sass.js"></script>
        <style id="csscode"></style>
        <script>
          Sass.initialize('bower_components/sass.js/dist/sass.worker.js');
          function compileCSS(color) {
          var options = {};
          Sass.compile('$color: ' + color +  '; h1 { color: $color; }', function(result){
              $('#csscode').html(result.text);
          });
          }
          compileCSS('orange');      
        </script>
    </head>
    <body>
    <h1>Colored text</h1>
    <form>
      Enter color name and hit enter:
      <input type="text" value="orange" name="color" />
      <input type="submit" />
    </form>
    <script>
          $( 'form' ).submit(function(event) {
          color = $( 'input[name="color"]' ).val();
          compileCSS(color);
          event.preventDefault();
          });   
    </script>    
    </body>
    </html>
  2. Now open demo.html in your web browser. It will look like the following screenshot:
    How to do it...
  3. Test the demo by entering another color name in the input field and pressing submit. You will find that the color of the colored text will change according to your input.

How it works...

Every time you hit the submit button, the sass.js compiler will compile the following code:

$color: {color};
h1 { color: $color; }

With {color} depending on your input, your input should be a valid color name. The 147 color names defined by the Scalable Vector Graphics (SVG) are according to their specifications used by HTML and CSS3 too. See also http://www.w3.org/TR/css3-color/. You can use any valid CSS color value in Sass, so rgb(0,255,255) or even rgba(0,255,255,0.5) can be used too. You can read more about color usage in Sass in the Color functions recipe of Chapter 5, Built-In Functions.

The demo uses jQuery to insert the compiled CSS into the DOM (in line with the tag of the head section). jQuery is a feature-rich JavaScript library that can be used for HTML document traversal and manipulation, and event handling. Neither Sass nor sass.js requires jQuery for compiling.

In the Editing and debugging your Sass code in browser recipe of Chapter 2, Debugging Your Code, you can read how to debug your Sass code in a browser using the Google Chrome browser. Although the code of this recipe runs in a browser, the sass.js compiler is not used here. In browsers, debugging uses the Ruby Sass compiler with the watch function or LibSass with live reload.

There's more...

As it has already been made clear, you should not use sass.js for production in the first place. When you use Sass for a demo proposal as in this recipe, and you need to compile Sass based on user input, you can reduce the total load time leveraging a web worker. A web worker is a JavaScript that runs in the background, independently of other scripts. Sass.js ships with a web worker, which can be invoked as follows:

<script src="dist/sass.js"></script>
<script>
  // telling sass.js where it can find the worker,
  // url is relative to document.URL
  Sass.initialize('dist/sass.worker.js');

Because sass.js runs in a browser and does not have access to your files' system, you should register individual files before using them with the @import directive. The following is an example code that shows you how to register files:

Sass.writeFile('one.scss', '.one { width: 123px; }');
Sass.writeFile('some-dir/two.scss', '.two { width: 123px; }');
Sass.compile('@import "one"; @import "some-dir/two";', function(result) {
  console.log(result.text);l
  });

See also

Writing Sass or SCSS

Attentive readers have possibly already noticed that the SCSS code has been used to write Sass code. SCSS is the newer and more CSS-like syntax for Sass. This book uses SCSS code in lieu of the older indented Sass syntax. In this recipe, you will learn the differences between the Sass and SCSS syntaxes and why this book prefers SCSS.

Getting ready

For this recipe, you will need only a text editor and the Ruby Sass gem installed. In the Installing Sass for command line usage recipe of this chapter, you can read about how to install the Ruby Sass gem.

How to do it...

Use the following steps to learn how to convert SCSS code into the indented Sass syntax and find out that both syntaxes compile in exactly the same CSS code:

  1. Use your text editor to create a simple SCSS file called test.scss. This file should contain the following SCSS code:
    $color: orange;
    
    p {
     color: $color;
    }
  2. Then, run the following command in your console:
    sass-convert test.scss test.sass
    
  3. The command from the previous step will create a new file named test.sass. Now, open the test.sass file with your text editor and you will find that its content looks as follows:
    $color: orange
    
    p
      color: $color
  4. Now, you can run both the sass test.sass and the sass test.scss commands in your console. Both will give the following output:
    p {
      color: orange; }

How it works...

Currently, two syntaxes are available to write Sass: the original indented syntax, mostly called Sass, and also the newer Sassy CSS (SCSS) syntax, which is an extension of CSS3.

When running the sass test.sass and the sass test.scss commands, the compiler uses the file extension to decide which syntax should be used. In your project, you can import partials in either syntax without any problem. Again, the compiler knows what to compile based on the file's extension. In the Working with partials recipe of this chapter, partials are discussed in more detail.

The sass-convert command-line tool used in this recipe ships with the Ruby Sass gem. After installing the gem, you can directly run the sass-convert command. This command looks at the file extensions too; .sass is converted into .scss or vice versa.

There's more...

As you already know, Sass has been written in Ruby. Ruby is the programming language. You can also use Ruby with Ruby on Rails. Ruby on rails is the Ruby framework for creating web apps. Ruby uses both Sass and HAML. HAML is a markup language used to clearly and simply describe the HTML of any web document without the use of inline code. HAML is a template system for HTML that tries to avoid repetition of code and unnecessary characters by relying on indentation and not the text to determine where the elements and blocks of code begin and end.

The original Sass syntax used the same method of declaration and coding that Ruby does and relies on indentation, as HAML does. This syntax is an excellent fit in Ruby (on rails) and feels already familiar for Ruby developers.

The newer SCSS focuses on the proposal of Sass in being an extension of CSS. Not only does SCSS look like CSS, but any valid CSS code is valid SCSS code too. Because this book is not only intended for Ruby developers, but for anyone who wants to learn Sass, this book uses the newer SCSS syntax for Sass.

See also

Choosing your output style

When compiling Sass code into CSS code, you can choose between four different output styles: expanded, nested, compacted, and compressed. The nested style is the default style. In this recipe, you will learn the differences between these output styles and how to choose one for your projects.

Getting ready

You should have the Ruby Sass command line ready, as described in the Installing Sass for command line usage recipe of this chapter. You will also need a text editor.

How to do it...

Perform the following step to see the differences between the Sass output styles:

  1. Create an output.scss file and type the following Sass code into it:
    $base-color: blue;
    $link-color: orange;
    $hover-color: red;
    
    p {
      color: $base-color;
      
      a {
        color: $link-color;
        
        &:hover {
          color: $hover-color;
        }
        
      }
    }

    After creating the file mentioned earlier, you should compile this file into CSS with the four different output style options.

  2. Firstly, compile the output.scss file with the option by running the following command in your console:
    sass --style expanded output.scss
    

    The preceding command outputs the CSS code as follows:

    p {
      color: blue;
    }
    p a {
      color: orange;
    }
    p a:hover {
      color: red;
    }
  3. Then, run the following command:
    sass --style nested output.scss
    

    The preceding command outputs as follows:

    p {
      color: blue; }
      p a {
        color: orange; }
        p a:hover {
          color: red; }
  4. The third command you run will be:
    sass --style compacted output.scss
    

    The third command outputs the following CSS code:

    p {
    
      color: blue; }
    
    p a {
    
      color: orange; }
    
    p a:hover {
    
      color: red; }
  5. Finally, run the following command:
    sass --style compressed output.scss
    

    The last command outputs the following line of CSS code:

    p{color:blue}p a{color:orange}p a:hover{color:red}

How it works...

Sass enables you to choose your output style by setting the --style command-line flag. In this recipe, you have seen the different output styles of Sass. The first expanded style produces CSS code formatted in a manner that would allow you to write it yourself when directly coding your CSS code. In fact, the output has not got any special syntax or format.

The second and default style you have tried is the nested style. In the Using nested selectors recipe of Chapter 4, Nested Selectors and Modular CSS, you can read about the ability of nesting selectors in Sass. The nested style makes the nesting of selectors in your Sass code visible in the compiled CSS code by adding additional indents before the selectors that are nested. Notice that the real nesting of selectors is not possible in a valid CSS code, so the selectors are not nested in the compiled CSS. Because the indent helps reflect the structure of the CSS styles and the HTML document, it will make your code more readable and easier to debug. In Chapter 2, Debugging Your Code, of this book, you can read more about testing and debugging your Sass and compiled CSS code.

Finally, the compact and compressed output styles reduce the file size of the compiled CSS code. The fewer the number of bytes of the CSS code to download, the faster your website or app will load, which improves user experience too. The compact output style reduces the number of white space by not having nesting and each selector on a single line, while the compressed output style only has minimal white spaces required to meet the CSS specification. When using the compressed output style, the compiled CSS code has no whitespace except that necessary to separate selectors and a newline at the end of the file.

The compact output style and especially the compressed output styles are not intended to be read by humans. In most situations, you will use the default nested output style for the development stage of your project. When taking your project into production, you should compile your CSS code with the compressed output style. When you are using CSS source maps to debug your code, as described in the Using CSS source maps to debug your code recipe of Chapter 2, Debugging Your Code, your output style for the development stage does not matter.

The compressed output styles also remove all your comments. You can read how to comment your code and which comments are preserved in the Commenting your code in SCSS syntax recipe of Chapter 2, Debugging Your Code.

There's more...

When using Compass, as described in Chapter 6, Using Compass, of this book, to compile your Sass code, you can choose the same output styles as described in the previous section. Output styles are set in the config.rb file of your Compass project. When not explicitly setting the environment option to production, Compass uses the expanded output style. In the production environment the compressed output style had been used.

You have already read that the compressed output style removes all the extra white space. Also, colors are converted to their shortest notation. Further optimization of your CSS code is possible, but it is not a task for Sass. Postprocessors, such as clean-css, also perform a more advanced optimization of your CSS code like selector, property, and media query merging. In the Automatically prefixing your code with Grunt recipe of Chapter 16, Setting up a Build Chain with Grunt, you can read about how to integrate the clean-css plugin and other postprocessors into your build chain.

See also

You can find the clean-css CSS minifier for node.js at https://github.com/jakubpawlowicz/clean-css.

Working with partials

When your project grows, you should not put all your SCSS code in the same file. You will have to find some logic to organize your Sass files. Splitting up your code over multiple files and applying the modularization of your code will help you create maintainable and reusable code. In this recipe, you can read about partials. Partials are special Sass files that can be imported in your project, but the partials themselves are not compiled into CSS.

Getting ready

This recipe requires the Compass installed as described in the Installing Compass recipe of this chapter. You can edit the Sass code in your favorite text editor.

How to do it

The steps beneath will show you that partial file are not compiled into the CSS code:

  1. Create a file structure like the one shown in the following image:
    How to do it
  2. The main.scss file should contain the following Sass code:
    @import 'layouts/grid';
    
    // scss-lint:disable PlaceholderInExtend
    section.custom {
        @extend .row;
    }
  3. Write the following code beneath in the layouts/_grid.scss file:
    .row {
          width: 100%;
    }
  4. Now run the following command in your working directory:
    compass compile --force
    
  5. After running the compile command, a new stylesheets/main.css file will be generated. This file should contain the compiled CSS code, as shown here:
    /* line 1, ../sass/layouts/_grid.scss */
    .row, section.custom {
      width: 100%;
    }
  6. Finally notice that layouts/_grids.scss does not compiles into a CSS file, because of it is a partial file and only its code is use to generate output in them main file.

How it works...

Sass files beginning with an underscore are called partials and won't be compiled to CSS, but they can be imported into other Sass stylesheets. Partials are useful for modularizing your code. When you split up your code into different files based on the type of function, you can easily reuse your code. When you modularize your code and use a file's structure with partials that reflects the modularization strategy, it will also be a lot of easier to find the needed code when you have to maintain your applications.

In this recipe, the partial has been imported with the @import directive; you can read more about this directive in the Importing and organizing your files recipe of Chapter 9, Building Layouts with Sass. Compass compiles all the files in the Sass folder, but ignores partial files starting with an underscore (_). When compiling your code with node-sass, as described in the Using the sass-gulp plugin with Gulp recipe of this chapter, files starting with an underscore are also ignored by default.

When you compile your project on the command line, you mostly automatically compile only the main file, as the command line compiler only accepts a single input file.

Also, the @extend directive possibly requires some more detailed explanation. You can learn more about the @extend directive in the Utilizing the @extend directive recipe of Chapter 4, Nested Selectors and Modular CSS. Finally, you should also notice that although the layouts/_grid.scss partial does not generate a compiled layouts/grid.css file, the .row selector declared in this partial outputs in the compiled stylesheets/main.scss CSS file. In the Using placeholder selectors with the @extend directive recipe of Chapter 4, Nested Selectors and Modular CSS, you will learn how to use the @extend directive, which prevents output in the compiled CSS. Also, mixins, as described in the Leveraging mixins recipe of Chapter 3, Variables, Mixins, and Functions, are not outputted in the final CSS code.

There's more…

Choosing a strategy to split up or modularize your code is not that easy. In the Applying the OOCSS, SMACSS, and BEM methodologies recipe of Chapter 4, Nested Selectors and Modular CSS, you can read about OOCSS, SMACSS, and BEM; these methodologies help you create modular, reusable, and maintainable CSS code. Applications and web pages are split up into modules and responsibilities, and each of them gets its own partial. Directory structures with partials can reflect your architectural strategy.

Hugo Giraudel, who maintains the Sass Guidelines project, introduced the 7-1 pattern: 7 folders, 1 file. The 7-1 pattern based on SMACSS starts with the following file structure:

There's more…

Many projects will fit in the preceding structure, but you should realize that architecture is mostly very specific to the project. Depending on your project, you possibly should adapt the 7-1 pattern or even choose a quite different solution.

See also

Writing your code in a text editor

You can write your Sass code in any text editor. Those who are familiar with the command line will even prefer an editor like VIM. VIM is an improved version of the vi editor distributed with most UNIX systems. This recipe will show you that you do not only have to choose your editor, but also have to find some SCSS style guidelines that fit your needs.

Many text editors have syntaxes highlighting for Sass and SCSS code. People who prefer a GUI should check out the See also section of this recipe.

Getting ready

You will only need your favorite text editor for this recipe.

How to do it…

Use the following steps to set up a new project according the style guidelines:

  1. Read the SCSS style guidelines from the See also section and write down the style guidelines you are going to use when writing Sass code.
  2. Set up your text editor to use a default indent according to the style guidelines from the previous step.
  3. Open a new project and create a file structure. See the Working with partials recipe of this chapter to read more about file structures and Sass application architectures.
  4. When you intend to use Compass, you can also run the compass init command, which automatically sets up an initial file structure for your project.

How it works...

Style guidelines will tell you how to write your code and guarantee that all the team members can work together on the same code base without spending too much time understanding the other's code. The guidelines should describe the indent in your code and how to nest your selectors. Also, naming conventions are part of the style guidelines. The names of your variables should not only be meaningful and descriptive, but they should also follow the guidelines. Sass variables are explained in Chapter 3, Variables, Mixins, and Functions, of this book.

Which style guidelines you chose does not matter so much, but when you have chosen, you should apply them correctly and consistently. Style guidelines keep your code readable, scalable, reusable, and maintainable.

Alternatively, you can use the scss-lint tool. This tool helps keep your SCSS files clean and readable. You can run it manually from the command line. You can find and read more about the scss-lint tool at http://davidtheclark.com/scss-lint-styleguide/.

The code examples in this book have all been linted with the scss-lint tool. When linting the code, the ColorKeyword linter will be excluded:

scss-lint --exclude-linter ColorKeyword

The ColorKeyword linter checks for usages of the HTML color keywords. The guidelines of the scss-lint tool tell you to use the (short) hexadecimal color notation instead of color keywords. In the examples in this book color names are used because of they are more easy to read.

In some situations, guidelines are ignored when the examples have to show a Sass feature that does not meet the guidelines. So, the PlaceholderInExtend linter does look for usages of the @extend directive without a placeholder, while the Working with partials recipe of this chapter explicitly shows you how the @extend directive can output without using a placeholder.

Also, plugins for the scss-lint tool are available for the VIM, IntelliJ, Sublime Text, Atom, and Emacs editors.

There's more...

In the Editing and debugging your Sass code in a browser recipe of Chapter 2, Debugging Your Code, you can read how to write and debug your Sass code in a browser. Editing in a browser does not require a text editor at all. When editing your code in a browser, you should not ignore the style guidelines.

See also

Style guidelines

Next, you will find an overview of different style guidelines for SCSS. Read them and choose the one that best fits your needs. Feel free to combine more than one source to create your own unique guidelines:

GUIs for Sass

Those who do not want to work with the command line can search for a suitable GUI or application. Many text editors can highlight that Sass and SCSS code have abilities to compile and preview your code. Some editors can also run post process tasks for the compiled CSS code. They are as follows:

  • Brackets is a modern, open source text editor that makes it easy to design in the browser. Brackets focuses on visual tools and preprocessor support and is released under the MIT License. You can use Brackets free of charge, and it runs on OS X, Windows, and Linux. Download Brackets at http://brackets.io/.
  • Sublime Text is a sophisticated text editor for code, markup, and prose according its website. Sublime Text may be downloaded and evaluated for free; however, a license must be purchased for continued use. A per-user license will cost $70. Read more about Sublime Text at https://www.sublimetext.com/.
  • Prepros is a tool to compile LESS, Sass, Compass, Stylus, Jade, and much more with automatic CSS prefixing. It comes with a built-in server for cross-browser testing. It runs on Windows and Mac. Prepros has a free trial version, and you can buy a single user license for $29. More information on Prepros can be found at https://prepros.io/.
  • Finally, there's Compass.app that is a menubar-only app for Sass and Compass. It helps designers compile stylesheets easily without resorting to a command-line interface. Compass.app is available for OS X, Windows, and Linux. You can buy Compass.app for only $10 at http://compass.kkbox.com/.
Left arrow icon Right arrow icon

Key benefits

  • Leverage Sass to make your CSS code maintainable, reusable and prevent code duplications
  • Shorten debug time with Sass when creating complex CSS code for different browsers and devices
  • Write easy and bullet-proof CSS with Compass using this step-by-step and detailed guide

Description

Sass and Compass Designer's Cookbook helps you to get most out of CSS3 and harness its benefits to create engaging and receptive applications. This book will help you develop faster and reduce the maintenance time for your web development projects by using Sass and Compass. You will learn how to use with CSS frameworks such as Bootstrap and Foundation and understand how to use other libraries of pre-built mixins. You will also learn setting up a development environment with Gulp. This book guides you through all the concepts and gives you practical examples for full understanding.

Who is this book for?

This book is mainly intended for web developers and designers who are comfortable with CSS and HTML. If you are someone with some experience with CSS, you will find the learning curve of learning Sass syntax to be less steep. Basic knowledge of web development is helpful but you don't have to be a programmer to understand Sass.

What you will learn

  • Spend less time debugging code
  • Compile Sass code into readable and maintainable CSS
  • Integrate Sass in your own projects
  • Reuse your code to prevent code duplications
  • Write reusable and portable CSS code
  • Make use of pre-built and established code written by other developers
  • Reduce development and maintenance time of your projects
  • Set up a development environment with Gulp
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 29, 2016
Length: 436 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286935
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Publication date : Apr 29, 2016
Length: 436 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286935
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,396.97
Bootstrap 4 By Example
₹3649.99
Mastering Sass
₹3649.99
Sass and Compass Designer's Cookbook
₹4096.99
Total 11,396.97 Stars icon
Banner background image

Table of Contents

17 Chapters
1. Getting Started with Sass Chevron down icon Chevron up icon
2. Debugging Your Code Chevron down icon Chevron up icon
3. Variables, Mixins, and Functions Chevron down icon Chevron up icon
4. Nested Selectors and Modular CSS Chevron down icon Chevron up icon
5. Built-in Functions Chevron down icon Chevron up icon
6. Using Compass Chevron down icon Chevron up icon
7. Cross-Browser CSS3 Mixins Chevron down icon Chevron up icon
8. Advanced Sass Coding Chevron down icon Chevron up icon
9. Building Layouts with Sass Chevron down icon Chevron up icon
10. Building Grid-based Layouts with Susy and Sass Chevron down icon Chevron up icon
11. Foundation and Sass Chevron down icon Chevron up icon
12. Bootstrap and Sass Chevron down icon Chevron up icon
13. Meeting the Bourbon Family Chevron down icon Chevron up icon
14. Ruby on Rails and Sass Chevron down icon Chevron up icon
15. Building Mobile Apps Chevron down icon Chevron up icon
16. Setting up a Build Chain with Grunt Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
David Akinci Jul 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Darshana Ghodke Distribution Executive from Packt Publishing asked me to review this book.Normally I'm not a great fan of technical Cookbooks, because most of the time they miss just what you are looking for or are not easy in finding/showing wanted information. Bass Jobsen clearly took an other approach and created a well structured, logic and easy to read book. As a Bootstrap-3 developer I work with LESS, but the latest Bootstrap-4 is using SASS. The most important steps to get you going with Bootstrap-4 and SASS are punctual described. Don't expect to find every little detail about Sass and Compass, but after reading this book your ready to work with it and discover more details during future designing no matter if it is in Bootstrap, Foundation, Susy, Bourbon, Ruby on Rails, Ionic and with the help of Grunt.
Amazon Verified review Amazon
Sjukun Ir Jun 19, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the first Packt's Cookbook that I read and I must say that I really like how they structured the book: Getting ready, How to do it, How it works, There's more, and See also. This structure makes it easy to learn and also to use the book as reference.This book is suitable for beginners to learn about Sass and Compass as well as for intermediate readers. The author did a good job to make it easy to read and learn. He included various topics about Sass and Compass such as variables, mixins, functions, nested selector and modular CSS, building layout, Foundation and Bootstrap, Bourbon family, mobile apps (ionic framework), etc. There is even a related topic about WordPress although I think it is better if the author included more topic about it.In short, I think beginners should have this book as their first book if they want to learn Sass and Compass.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela