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
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.
In this recipe, you will learn how to use Sass on the command line.
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/.
After installing Ruby, you can use the following steps to install Sass on your system:
Open a terminal or a command prompt. Mac users should run
Terminal.app
and Window users can use thecmd
command.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.Now, you should be able to check your installation by running a command, such as the following one:
sass -version
The preceding command should generate the following output:
Sass 3.4.13 (Selective Steve)
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.
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.
The website of the Ruby community can be found at https://www.ruby-lang.org/
You can read more about Ruby gems at http://guides.rubygems.org/what-is-a-gem/
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.
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.
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:
Create a new compass project with the following command:
compass create project
The preceding command will create a new folder called
project
, which will contain the files shown in this image:Now, you can compile your project by running the following command:
compass compile project
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.
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.
The official website for the Compass framework can be found at http://compass-style.org/.
You can run Sass on the command line to compile your Sass files directly into the CSS code.
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.
Use the following steps to find out how to compile your Sass code in the command line:
Create a Sass template called
first.scss
that contains the following SCSS code:$color: orange; p { color: $color; }
Then, run the following command in your console:
sass first.scss
You will find that the preceding command outputs the CSS code as it is shown here:
p { color: orange; }
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.
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.
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.
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.
Take a look at the following steps to understand how to use the Sass interactive mode:
You can start the interactive shell by running the following in your console:
sass -interactive
Now, you can enter the following code into the shell:
>> 1px + 1px
The preceding command will give the following output:
2px
Also, notice that you can only enter a valid code. Consider the following code:
>> 1px + 2em
Because Sass cannot sum different units, the preceding code will generate the following error:
SyntaxError: Incompatible units: 'em' and 'px'.
Also, Sass built-in function can be evaluated. Enter the following code into the shell:
change-color(#ff0000, $alpha: 0.5)
You will find that this returns the following output:
rgba(255, 0, 0, 0.5)
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.
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: #{ }
.
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.
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
The following step will show you how to use Gulp and gulp-sass
to compile your Sass code into CSS code:
Create an example Sass file called
main.scss
and save this file in thesass
folder. The content of this file can look as follows:$color: orange; p { color: $color; }
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')); });
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
The preceding command creates a new file called
css/main.css
. This CSS file contains the following CSS code now:p { color: orange; }
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.
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.
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/.
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.
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.
Here is how you can compile Sass code in your browser:
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>
Now open
demo.html
in your web browser. It will look like the following screenshot: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.
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.
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 });
You can read more about sass.js at https://github.com/medialize/sass.js.
Sass.js had been compiled with Emscripten. Emscripten is an LLVM-based project that compiles C and C++ into highly optimizable JavaScript in the asm.js format. You can read more about Emscripten at http://kripken.github.io/emscripten-site/docs/introducing_emscripten/about_emscripten.html.
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.
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.
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:
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; }
Then, run the following command in your console:
sass-convert test.scss test.sass
The command from the previous step will create a new file named
test.sass
. Now, open thetest.sass
file with your text editor and you will find that its content looks as follows:$color: orange p color: $color
Now, you can run both the
sass test.sass
and thesass test.scss
commands in your console. Both will give the following output:p { color: orange; }
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.
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.
In the Playing on SassMeister recipe of Chapter 2, Debugging your code, you can read about online test environments for Sass. Also, SassMeister has an option of switching easily between the SCSS and Sass syntaxes.
You can read more about HAML at http://haml.info/.
In Chapter 2, Debugging your code, you can read about how to use Sass with Ruby on rails.
Visit http://sass-lang.com/documentation/file.INDENTED_SYNTAX.html if you want to learn more about the indented syntax.
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.
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.
Perform the following step to see the differences between the Sass output styles:
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.
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; }
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; }
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; }
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}
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.
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.
You can find the clean-css CSS minifier for node.js at https://github.com/jakubpawlowicz/clean-css.
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.
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.
The steps beneath will show you that partial file are not compiled into the CSS code:
Create a file structure like the one shown in the following image:
The
main.scss
file should contain the following Sass code:@import 'layouts/grid'; // scss-lint:disable PlaceholderInExtend section.custom { @extend .row; }
Write the following code beneath in the
layouts/_grid.scss
file:.row { width: 100%; }
Now run the following command in your working directory:
compass compile --force
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%; }
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.
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.
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:
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.
Giraudel's Sass Guidelines project can be found at http://sass-guidelin.es/.
Vinay Raghu compared different Sass architectures and wrote an excellent blog post about it. You can find his blog post at http://www.sitepoint.com/look-different-sass-architectures/.
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.
Use the following steps to set up a new project according the style guidelines:
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.
Set up your text editor to use a default indent according to the style guidelines from the previous step.
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.
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.
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.
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.
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:
The Sass Guidelines project can be found at http://sass-guidelin.es/.
A Sass style guide published by Chris Coyier can be found at https://css-tricks.com/sass-style-guide/.
edX is a massive open online course provider and online learning platform. For developers, it is an easy-to-understand and compact CSS/Sass style guide available at https://github.com/edx/ux-pattern-library/wiki/Styleguide:-Sass-&-CSS.
Also, read An Auto-Enforceable SCSS Styleguide Powered by SCSS-Lint by David Clark at http://davidtheclark.com/scss-lint-styleguide/.
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/.