Improve CSS development with Sass

Incorporate programming flexibility and features

Syntactically awesome stylesheets (Sass) is a meta-language and cascading stylesheets (CSS) preprocessor. Understanding Sass principles is your key to faster, more efficient CSS development. Sass provides simple, elegant, and robust syntax for CSS so you can create manageable stylesheets. Learn the basics of using Sass to improve the stylesheets for your website in this introduction.

18 July 2013 - Added a resource item for the article, "Do more in CSS with LESS," to Resources).

Share:

Alex Starostin, QA Engineer, IBM

Photo of Alexander StarostinAlex Starostin is a quality assurance engineer at the IBM Australia Development Lab. His main focus is software testing and QA support for a development team in the agile environment. Apart from regular work duties, Alex likes to devote his time to learning new technologies and programming languages.



18 July 2013 (First published 28 May 2013)

Also available in Chinese Russian Japanese Vietnamese

If you develop stylesheets, Syntactically Awesome Stylesheets (Sass) can vastly improve the overall experience. Sass is a stylesheet language and cascading stylesheets (CSS) preprocessor that adds traditional programming attributes to CSS development. Sass introduces several programming features, including variables, logical nesting of styles, mixins, arguments, and inheritance. As you develop stylesheets for your website, Sass can significantly simplify your life by converting your Sass to standard CSS markup.

In this article, you learn the key principles of Sass. I include practical examples that demonstrate how to use Sass to make your CSS development faster and more efficient.

Sassy CSS (SCSS) is a superset of CSS3; any SCSS code is valid CSS code. The code examples in this article are SCSS.

Why Sass

Sass syntax

  • SCSS, the most common syntax, is a superset of CSS's syntax.
  • The indented syntax, .sass, is older and uses indentation of lines to specify blocks.

Sass is a robust, configurable, and feature-rich solution for CSS development. It uses a dynamic construct approach instead of the old style static CSS rules. To follow the same programming style you use in your day-to-day development, with access to programming language constructs, then Sass is the best choice. Sass will surprise you with its flexibility and feature-filled solutions.

CSS preprocessors are essential for every web development environment. They will:

  • Reduce your development time.
  • Apply the Don't Repeat Yourself (DRY) principle for CSS development.
  • Make your code cleaner and more readable.

Many CSS preprocessor technologies are available. This article uses Sass because it is flexible with many features.

Installing Sass

Sass is primarily implemented in Ruby, though other implementations exist. The first step is to install Sass through its Ruby components.

  1. Download and install Ruby if it is not already on your system:
    • Windows users: RubyInstaller for Windows
    • Mac OS X: Ruby is already installed in your operating system.
    • Linux: Install Ruby through your favorite packet manager.
  2. Install Sass Ruby gem with the following command: gem install sass

Preparing the Sass environment

Use your favorite text editor to create a file with the extension .scss. Text editors have varying levels of support for Sass. See Resources for a list of text editors with different levels of Sass syntax highlighting support.

Copy and paste the code from Listing 1 into the new .scss file.

Listing 1. Sass code sample
#blueBar {
position: relative;
height: 37px;
left: 0;
right: 0;
top: 0;
}

The Sass language is a superset of CSS3. In Sass version 3.2.1, all valid CSS is also valid Sass. The code from Listing 1 is valid CSS and is also valid Sass. Nevertheless, you still must to turn the Sass from Listing 1 into CSS. If you don't, web browsers cannot interpret your stylesheet properly. Rather than constantly turn your Sass into CSS with the sass-convert command, set up Sass to automatically convert your file to CSS every time you save. For Sass to automatically monitor your file, run the command in Listing 2 in your command-line application.

Listing 2. Monitor a file
sass --watch
style.scss:style.css

You can also use Sass to monitor an entire directory by using the command in Listing 3.

Listing 3. Monitor a directory
sass --watch
stylesheets/sass:stylesheets/compiled

Your framework is created, and Sass automatically converts your code to valid CSS any time you save your Sass file. Now, you can get started.


Variables

A key feature that is missing from CSS is the variable. Stylesheets tend to have much repetition. A helpful option is to write a value once and reuse it through its alias. For example, assume you have a stylesheet like the one in Listing 4.

Listing 4. CSS elements and colors
#someElement { color: #541B32; }
#anotherElement { color: #541B32; }
#yetAnotherElement { color: #541B32; }

Standard CSS dictates that you explicitly write all values, causing the redundancy in Listing 4. With Sass, however, you can gain the efficiencies in Listing 5.

Listing 5. Sass elements and colors
$purplishColor: #541B32;
#someElement { color: $purplishColor; }
#anotherElement { color: $purplishColor; }
#yetAnotherElement { color: $purplishColor; }

The benefit is clear. Now you can change the colors of your elements in one place. In Listing 5$purplishColor is a variable, so you can change it at any time in your Sass file. Sass variables have no type; you can assign a string, integer, or even a color to the same variable.


Modules

You can easily break your CSS code into individual modules for the Sass engine to pull together. With the @import directive, you can import modules, as in Listing 6. The directive takes a file name, a hyperlink, or any other path. Both CSS and SCSS files are loaded and coalesced into one document.

Listing 6. Sass importing modules
@import "colors.scss"
@import "links.scss"

How you break up your code in CSS and in Sass is fundamentally different. When you break CSS code into smaller stylesheets, each stylesheet takes a separate HTTP request to load. The Sass @import directive pulls the module code directly, so you always have one CSS file at the end.


Strings and interpolation

Sass supports strings concatenation and variables interpolation. Instead of using variables only for property values, you can also directly insert their values into property and selector names, as in Listing 7.

Listing 7. Sass strings and variables operation
$image_dir: 'images/web/';
$page: 10;

.button
{
background-image: url( $image_dir + 'image.gif' );
:before { content: "Page #{ $page }"; }
}

The code in Listing 7 is converted to the CSS in Listing 8.

Listing 8. CSS strings and variables operation
.button {
background-image: url("images/web/image.gif"); }
.button:before {
content: "Page 10"; }

Math

Sass supports standard math operators to operate with numbers, as in Listing 9. You can do simple math with your variable values.

Listing 9. Sass math operations on numbers
.block {
$block_width: 500px;
width: $block_width - ( 10px * 2 ) - ( 1px * 2 );
}

The code in Listing 9 is converted to the CSS shown in Listing 10.

Listing 10. CSS math operations on numbers
.block {
width: 478px; }

Math operations on colors are also supported, as in Listing 11.

Listing 11. Sass math operations on colors
.block {
$color: #010203;
color: $color;
border-color: $color - #010101;
}

The code in Listing 11 is converted to the CSS in Listing 12.

Listing 12. CSS math operations on colors
.block {
color: #010203;
border-color: #000102; }

Nesting selectors and properties

One of the most desirable features of CSS is nesting selectors (applying a style for a selector within a selector). To nest a selector in CSS, you must redundantly list the parent selector for each child selector you define. To streamline this process in Sass, you nest selectors, as in Listing 13.

Listing 13. Sass nesting selectors
#some {
border: 1px solid red;
.some { background: white; }
}

The code in Listing 13 is converted to the CSS in Listing 14.

Listing 14. CSS nesting selectors
#some { border: 1px solid red; }
#some .some { background: white; }

Control directives

Sass control directives provide flow and logic to your CSS code. The basic control directives that are covered in this section are @if, @for, and @each.

@if

Sass supports basic if/else functions and compiles them to CSS. For example, in Listing 15, you want the link color to be black in all cases except where the base color is already black. If the base color is already black then, you set it to white.

Listing 15. Sass @if example
$color: black;

.link {
@if $color == black {
color: white;
} @else {
color: black;
}
}

The code in Listing 15 translates to the CSS in Listing 16.

Listing 16. CSS @if example
.link {
color: white; }

The use of @if here works the same way as in other programing languages. The @if statement can be followed by several @else if statements and one @else statement. If the @if statement fails, the @else if statements are tried in order until one succeeds or the @else is reached.

@for

The @for directive repeatedly outputs a set of styles. For each repetition, a counter variable is used to adjust the output, as in Listing 17.

Listing 17. Sass @for example
@for $i from 1 through 5 {
.button-#{$i} { width: 1px * $i; }
}

The code in Listing 17 translates to the CSS in Listing 18.

Listing 18. CSS @for example
.button-1 {
width: 1px; }
.button-2 {
width: 2px; }
.button-3 {
width: 3px; }
.button-4 {
width: 4px; }
.button-5 {
width: 5px; }

@each

The @each directive takes the item from the list and outputs styles with the listed values, as in Listing 19.

Listing 19. Sass @each example
@each $company in IBM, Motorola, Google {
.#{$company}-icon {
background-image: url('/images/#{$company}.jpg');
}
}

The code in Listing 19 translates to the CSS in Listing 20.

Listing 20. CSS @each example
.IBM-icon {
background-image: url("/images/IBM.jpg"); }
.Motorola-icon {
background-image: url("/images/Motorola.jpg"); }
.Google-icon {
background-image: url("/images/Google.jpg"); }

Functions

You can apply functions in Sass. Plan to refactor and abstract the methods behind successful techniques so they are reusable and portable for the next project.

Sass has a long list of built-in functions. For example, you can use rgb() and darken(), as in Listing 21, to manipulate colors. You can change color hue, saturation, lightness, opacity, fluidity scale, and many more aspects. You can also define your own functions and reuse them when needed.

Listing 21. Sass functions
#someElement {
color: rgb(150, 50, 100);
}
#someDarkYellowElement {
color: darken(yellow, 33%);
}

The code in Listing 21 translates to the CSS in Listing 22.

Listing 22. CSS functions
#someElement {
color: #963264; }
#someDarkYellowElement {
color: #575700; }

Sass includes functions for mathematics, strings, lists, introspection, and more. See Resources for a complete list of Sass functions.


Mixins

A mixin, which reuses slices of your CSS code, is defined with the @mixin directive, as in Listing 23. With mixins, you define patterns of property value pairs that you then reuse in other rule sets. Mixins are useful for simplifying your stylesheets and improving their readability. Basically, @mixin is a user-defined function. Mixins also take arguments, which means you can produce a wide variety of styles with few mixins.

Listing 23. Sass mixins
@mixin rounded-corners($radius: 5px) {
border-radius: $radius;
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
}

#header {
@include rounded-corners;
}
#footer {
@include rounded-corners(10px);
}

The code in Listing 23 translates to the CSS in Listing 24.

Listing 24. CSS mixins
#header {
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px; }

#footer {
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px; }

Functions and mixins are similar. They both accept variables, but they are different in that a function always returns a value and mixin output is lines of code.


Compass

Compass is an open source CSS authoring framework that uses the Sass stylesheet language. Its several reusable design patterns (that use mixins) help you construct solid, powerful stylesheets. The Compass library of common code is an indispensable tool in Sass development.

Essentially, Compass is a wrapper for CSS. It handles common CSS problems such as browser compatibility, layouts, and stylesheet optimizations through spriting and other techniques.

Like Sass, Compass comes packaged as a Ruby gem. To install Compass, enter gem install compass from the command line.

You can now use mixins (functions) that are defined in the Compass framework. There are many predefined functions, classes, and native CSS3 support in Compass. For more information about Compass, see Resources.


Conclusion

This article provided an introduction to several concepts that can help you successfully implement Sass on your website. You learned about variables, interpolation, nesting, functions, and some directives.

Sass is not the only CSS preprocessor on the Internet. Its closest competitor, LESS (see Resources), also commands some market share. Ultimately, the differences between Sass and LESS are small. Sass's most important asset is Compass, an extension that is missing in LESS. It is important to try as many preprocessors as possible to determine which one fits your style and matches your needs.

Resources

Learn

Get products and technologies

Discuss

  • Get involved in the developerWorks community. Connect with other developerWorks users as you explore the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=930959
ArticleTitle=Improve CSS development with Sass
publish-date=07182013