Sass Essentials - Sample Chapter
Sass Essentials - Sample Chapter
ee
P U B L I S H I N G
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Sass Essentials
$ 29.99 US
19.99 UK
pl
Alex Libby
Sass Essentials
Sass Essentials
Sa
m
Develop efficient and streamlined CSS styles using Sass for any
website or online application with minimal effort and maximum
scope for reusability in future projects
Alex Libby
Preface
Picture this sceneyou consider yourself pretty au fait with developing CSS styling;
you've produced some stunning work over the years, spending time carefully
crafting styles for demanding clients.
A colleague starts to band this word "Sass" around the officeyou soon hear others
talk of this "Sass" on Twitter and begin to wonder what it's all about.
Well, fear no morewelcome to the world of Sass! Throughout the course of this
book, we'll delve into the world of CSS preprocessing, where we will explore tips
and tricks that can help you make your CSS development more efficient, using Sass.
Of course, you're probably wondering how; all will be revealed. Consider this as a
taster thoughhow often have you spent time choosing colors for buttons only to
find out that the client doesn't like the color scheme.
Sound familiar? I'll bet the answer is yes. In the next few pages, I will show you the
tricks you need to know to create a color scheme from a single color. Let's just say
that should you find out that your clients want the color changed, long evenings of
changing code will become a thing of the past.
Let's dive in and start our journey through the world of Sass.
Preface
Chapter 2, Creating Variables and Mixins, explores a key facet of Sass in the form of
using variables. It discusses how editing one value can automatically update a whole
series of rules at a single stroke. Just imagine altering the font sizes for your website
in one go by simply editing one number!
Chapter 3, Building Functions, Operations, and Nested Styles, talks about how to use
functions and operators to construct an entire site from just a handful of variables.
We will also touch on nesting styles to help make code easier to read and maintain.
Chapter 4, Directing Sass, takes a look at another key element of Sass in the form of
directives. It provides information on how to use some of the more popular options,
such as @extend or @media. These will be used to a great effect in a series of demos,
which quickly illustrates how careful use of these directives can have a significant
positive effect on our code.
Chapter 5, Incorporating Sass into Projects, examines how to apply some of the tips and
tricks we have covered throughout the book into more practical uses. It talks about
several popular frameworks, such as Bootstrap, WordPress, and CSS grids. This
chapter also shows you how Sass can be used to great effect to help construct sites,
while reducing the amount of code we need to write.
Creating variables
[ 31 ]
2. Ruby will go away and fetch the package and its dependencies. When
completed, it will display a message confirming how many gems have
been installed:
[ 32 ]
Chapter 2
4. In the textbox, enter install and select Package Control: Install Package
from the list:
5. Sublime Text will retrieve the list of available packages. In the drop-down
box, enter SublimeLinter to display the item in the list. Then, click on it to
install the plugin:
[ 33 ]
7. Repeat steps 4 and 5, but this time, enter linter jshint and click on
SublimeLinter-jshint to install the SublimeLinter JSHint plugin.
8. Repeat steps 4 and 5 once more, but this time, enter linter scss and click
on SublimeLinter-contrib-scss-lint to install the SublimeLinter SCSS plugin:
SublimeLinter is now installed. We've set Sublime Text to automatically check our
code for any potential errors and alert us in the event of an issue with our code. To
make it really effective though, we need to make a few changes:
1. First, bring up the command palette as before (or by pressing Shift + Ctrl + P
for PC/Linux or Command + Ctrl +P for Mac). Then, enter gutter and select
SublimeLinter: Choose Gutter Theme from the list.
[ 34 ]
Chapter 2
2. From the list that appears, choose Knob Symbol to change the icons that
show in the left-hand side margin when there is an issue in the code.
3. We will also alter the style used to mark our code if there is an issue; fire up
the command palette as before. Then, enter mark to select SublimeLinter:
Choose Mark Style and select Squiggly underline from the list.
4. We can now check to see whether it works. Restart Sublime Text. Then, open
up the sassfunctions.scss file from Chapter 1, Introducing Sass.
5. Press Ctrl + S to save. While we haven't changed our code, it's enough to
trigger the linter to kick in, as shown in the following code:
Okay. Now, we have our helping hand in place. We're now ready to start writing
code; we'll begin with creating variables to help with assigning values in our code.
[ 35 ]
2. Delete the files in the css folder. This is to verify that they have indeed been
created when we rerun the process.
3. If the Grunt process is still running, then stop and restart it. If all is well,
we should see it recreate the missing CSS and map files. Note that they
won't be listed, but a check of the timestamp on each file in the css folder
will confirm whether or not they have been recreated, as shown in the
following screenshot:
[ 36 ]
Chapter 2
You may have noticed the style value that is set to expanded. If we
change this to compressed, then it will compress each CSS file that is
created. There is also an autoprefixer task included in this Grunt file;
we will cover this in more detail later in the Animating content using
Sass section.
Creating variables
Let's stay with the sassfunctions.scss file that is open from the previous exercise.
If you take a careful look at lines 7 to 10, you will see this:
These are examples of variables or placeholders for values within our code. These
work in a similar fashion to JavaScript libraries, such as jQuery. To see how they
work, let's go through the following steps:
1. Fire up a Node.js command prompt and change the location to our project
area. In this command prompt, enter the following code and click on Enter:
grunt
Grunt will kick in and compile the file. If we open it up, we can see that it has
produced a valid CSS file, as shown in this screenshot:
[ 37 ]
Sass will convert colors to the RGBA format during compilation. You will
note that we have rgba(51, 34, 17, 0.7) shown in the code; this is the
RGB equivalent of #321, but is displayed in the RGBA format as a result of
setting the additional alpha value of 70%.
We can refer to a site (such as http://www.rgbtohex.net/)
to confirm whether the RGBA values displayed in our code do
indeed match those shown in the compiled CSS.
You will notice that we have comments displayed in our code. Sass uses the
Variables can be used to store any value. Once created, they will replace the instance
with that value. Variables are controlled by scope, which limits where they can be
used; in most cases, it makes sense to define them at the top of the style sheet or even
in a separate imported file. Even though the file may be large, Sass will only use
those variables that are explicitly referenced within our code.
For more details on how scope limits the use of variables, refer
to http://sass-lang.com/documentation/file.Sass_
REFERENCE.html#variables_.
It is worth getting to know the different data types available in Sass. In brief, the
following types are available:
Strings of text, with and without quotes (for example, "foo", 'bar',
and baz)
[ 38 ]
Chapter 2
Maps from one value to another (for example, (key1: value1, key2
value2))
For now, let's switch to one use of variables, where it is important to get it rightthat
of assigning colors.
and so on.
Seems pretty reasonable, right? If we wanted to change a particular shade of color
to another value (say, make it lighter), we would go through it and change every
instance in our code, right?
You can, but I won't. That's too much like hard work! Instead, let's use Sass to better
manage our colors. The sensible way to do this is through a two-step process:
1. First, let's assign proper names to our variables. Instead of trying to decipher
hex codes or even RGB(A) values, we will know that #327DA0 is dark blue,
for example:
$darkBlue: #327DA0;
$darkRed: #a03246;
$darkYellow: #a08c32;
[ 39 ]
2. Next, let's assign these color names to variables. One way of doing this is from
Jim Nielsen, the designer, who recommends following the generic-specific
principle, where we use functional names followed by descriptive names:
Let's see how this makes sense and avoids any issues with changing color values. We
can group all the generic items together (in this case, $border), follow it by the color
(blue), and tack on any additional descriptors, such as light or dark.
The key though is to remain consistent. Throughout this book, we will use
camelCase, but we could equally use hyphenated names if we wanted to;
it is up to you to decide what format suits your needs.
For more details on this useful tip by Jim Nielsen, head over to
http://webdesign.tutsplus.com/articles/quick-tipname-your-sass-variables-modularly--webdesign-13364.
Using this principle means that we need to change the color for a specific category
of link, for example, we only need to change it in one place and recompile our code.
It has the added bonus of avoiding any issues where the same link color variable is
reused in different scenarios such as this:
$colorText: #333333;
$colorLink: #001eff;
.myClass {
color: $colorText;
border-color: $colorLink;
[ 40 ]
Chapter 2
}
a {
color: $colorLink;
}
In this instance, we've reused the $colorLink variable in two different rules.
If we wanted to change the border color, and not the link color, then we would've
created a problem.
Let's put this into practice with a quick and easy demo. We'll set up a row of simple
boxes and assign colors using variables:
1. We start with extracting copies of colorvariables.html. Go ahead and save
this in the root of your project area.
2. In a new file, add the following Sass code. This takes care of styling our
boxes, starting with the creation of six color variables:
$darkBlue: #327DA0;
$darkRed: #a03246;
$darkYellow: #a08c32;
$darkPink: #a0327d;
$darkOrange: #a05532;
$darkCyan: #32a08c;
$white: #fff;
3. Next comes the assignment of these color variables to the box colors:
$colorBox1:
$colorBox2:
$colorBox3:
$colorBox4:
$colorBox5:
$colorBox6:
$darkBlue;
$darkRed;
$darkYellow;
$darkPink;
$darkOrange;
$darkCyan;
4. Then comes the generic styling for all six boxes, where we set the size and
position on screen:
body {
font: 1.2rem bold
Helvetica, sans-serif;
color: $white;
}
div {
height: 5rem;
width: 5rem;
[ 41 ]
{
{
{
{
{
{
background-color:
background-color:
background-color:
background-color:
background-color:
background-color:
$colorBox1;
$colorBox2;
$colorBox3;
$colorBox4;
$colorBox5;
$colorBox6;
}
}
}
}
}
}
8. If all is well, we should see a nice set of boxes on screen when previewing
the code. It will display boxes using the colors that we've assigned in the
variables section of our Sass file:
See how easy it is? If we need to make a change, then the least we have to do is
change our code in two places and recompile it. For example, if we were to change
the shade of color used, then all we need do is change the hex value from step 2 and
recompile it.
If, however, we wanted to change the color of the boxes to a completely different
color, then we would need to either change or add the value as before, but this time,
also alter the value assigned to the affected $ colorBoxX variable from step 3.
[ 42 ]
Chapter 2
There are pitfalls with how we name our color variable. For insight
into some of the pitfalls we may face, take a look at the article by
Ben Smithett at http://bensmithett.com/stop-using-somany-sass-variables/.
2. This will start Grunt running, which is ready to compile changes to our code.
3. Next, open up a copy of the colorvariables.scss file from the previous
demo and copy lines 1 to 6 to a new file. Save the new file as _colors.scss
in the _partials folder in our project area.
4. Switch back to colorvariables.scss, remove the first six lines, and replace
them with the following code at the top of the file:
@import "_partials/_colors";
[ 43 ]
5. Revert back to the colorvariables.scss file and save this file as cvimport.
scss. If all is well, Grunt will kick in and recompile our code automatically.
6. Check inside the project area. We should not see any compiled CSS files with
the color names, but will see the color values used in cvimport.css.
The key though is that we should see no visual change to our demo when previewed
in a browser, but we can rest in the knowledge that we've restructured our code to
make it easier to manage. To really prove that we are indeed importing the files, use
a DOM Inspector to view the contents. Here, we can see links to the compiled style
sheet and both Sass files from within Firefox's inspector:
Now that we've compiled our files, there are a couple of points that we need to
be aware of. Take a look at the @import statement and note the following points
about it:
The file we've imported doesn't specify an extension. This is perfectly fine in
Sass. As long as a file exists with this name, it will import it with or without
an extension.
[ 44 ]
Chapter 2
Okay, let's move on to the next step. Now, we will take a look at how to create
mixins or blocks of code that you can literally "mix-in" to existing code. We can use
these to build up a library of existing code that can be pulled into future projects.
However, before we do so, I want to cover one small, but key part of Sasswhat
if we want to add comments to our code so that we know what it's all about if we
revisit it at a later date?
Adding comments
If you've spent any time developing code (which I am sure you have!), then you will
no doubt be used to adding comments. We can easily apply the same principles to
Sass files.
Comments in Sass usually take the form of either // or /* */. The former is usually
used for one-line statements and the latter for an entire comment block, as shown in
this screenshot:
All we need to do is add the appropriate comment with either single line or multiline
mode and compile the file. When it comes to compiling our Sass files though, there
are a couple of points we should be aware of:
Single line comments are dropped from the compiled CSS file when working
with Sass from the command line; only multiline comments are kept.
When we compile our SCSS file using Grunt, we may also wish to add a comment
to indicate the corresponding line in the source code. To do this, we can set
lineNumbers to true.
[ 45 ]
When we set the style of output in the Grunt file, we can choose to render our
compiled code in one of several ways:
Output style value
Result
expanded
nested
compact
compressed
Okay. We can now comment on our file (sorry, pun intended!); let's change focus and
take a look at how to build mixins using Sass.
Building mixins
At this point, we should be comfortable with making changes to and compiling our
code. Let's use some of our newfound knowledge to begin creating mixins that we
can reuse in our code.
[ 46 ]
Chapter 2
Mixins do as the name suggests. They allow you to "mix-in" blocks of code into our
existing projects, which reduces the amount of code we need to write because the
work has already been done.
This reduction of code is known as the DRY principle or
Don't Repeat Yourself. It's a key tenet of using Sass.
It's a simple block of code. The individual attributes within the block will be
recognizable. The two key points of note are that we introduce the block with
the @mixin keyword, followed by the name of the mixin.
The great thing about mixins is that we can easily reference them within other rules
in our code. As an example, we can use it to define the text style for a .page-title
class; all we need to do is include the highlighted single line of code:
.page-title {
@include large-text;
padding: 4px;
margin-top: 10px;
}
If we were to compile our code at this point, we will end up with this:
.page-title {
font-family: Arial;
font-size: 20px;
font-weight: bold;
color: #ff0000;
padding: 4px;
margin-top: 10px;
}
[ 47 ]
In this instance, Sass has swapped out the placeholder and replaced it with the
contents of the large-text mixin. To prove that this is indeed the case, we can add
this to an online compiler, such as sassmeister (http://www.sassmeister.com), as
shown in the following screenshot:
Hold on a moment! I hear you. As the code shown in the screenshot is actually more,
and not less, why would we want to do this?
Chapter 2
5. Grunt will kick in. If all is well, it will compile the code automatically;
we should see no difference visually in the output.
6. To prove that we are indeed importing the file, fire up the DOM Inspector
in your browser. If we do this in Firefox, we can see the proof in the Style
Editor tab:
The two added comment lines (starting with /*...) come directly from the source
map that we created automatically using Grunt. These are updated every time any
changes are made to our code.
We've only touched on the basics of including mixins. For more
details, it's worth taking a look at the official documentation for this
subject at http://sass-lang.com/documentation/file.SASS_
REFERENCE.html#including_a_mixin.
[ 49 ]
At this point, we're free to add additional mixins to our library file. We may only
have one mixin now, but over time, we can gradually build up a custom library of
mixins that can be used in future projects. If the mixin library gets too big, we can
always split them into smaller files and use an @import statement to compile the
smaller files into one larger library.
Let's change focus and move on. In sassfunctions.scss, something different
about the mixin that we moved, that is, it had additional parameters as part of
the mixin name.
[ 50 ]
Chapter 2
See, how easy it is! We will apply a standard border radius of 4px, but feeding in width
and height values of 5rem and 7rem respectively, as shown in the following screenshot:
[ 51 ]
"_partials/variables"
"_partials/typography"
"_partials/elements"
"_vendor/grid"
"_vendor/mixins"
These will contain our individual style rules, which we will add exactly as before.
Although we've used the standard @import syntax, it's worth noting that we can use
other formats too, such as importing multiple files into one statement, as shown in
the following code:
@import "_vendor/grid", "_vendor/mixins";
Either method will work. It's a matter of personal preference as to which method
you use.
When the main styles.scss file is compiled, it will compile the files into one master
style sheet. These files can be ones we've created specifically for the project, ones
we've reused from earlier projects, or ones from prebuilt mixin libraries available on
the Internet (as we will see later in this chapter).
Hold on a moment. Doesn't this mean that we'll end up with a bloated file that
contains lots of styles that we don't need? Yes! It will mean that if we are not careful,
we could end up with enormous style sheets; the trick is to ensure that we choose
the right mixin library to use (to avoid bloating) or extract the mixins we need and
discard the rest of the library.
[ 52 ]
Chapter 2
For more details on how to use the @import command in Sass, take
a look at the official documentation at http://sass-lang.com/
documentation/file.SASS_REFERENCE.html#import.
This is a simple, but really useful principle to grasp. In some respects, it is better
to use @extend to create new styles, rather than a mixin. Using a mixin will work
perfectly well, but it requires care and attention to ensure that we're only using those
attributes that we need, and not any that will lead to unnecessary bloat in our code.
There is a great article at http://alistapart.com/article/
dry-ing-out-your-sass-mixins that talks about how to dry out
your mixins with the use of @extend. It is worth a read, although it
does assume a certain amount of prior knowledge. The article on how
to use the @extend keyword by Hugo Giraudel at http://www.
sitepoint.com/sass-mixin-placeholder/ is also worth a read.
Okay, time to move on. We've built a number of different styles of mixins and
worked on how we can better structure our code through importing external
mixin files. However, do we really need to build lots of different mixin libraries?
Absolutely not. There is no sense in doing so if others have already created an
alternative and made it available online. Let's take a moment to look at a few
examples and see how we can incorporate them in our code.
[ 54 ]
Chapter 2
We've already seen that it is a simple matter of adding the relevant @import
statement at the head of our style sheet and then calling the appropriate mixin
using the @include keyword at the appropriate point in our code.
To show you how easy it is to use the imported mixin library, let's take a look at
the following example (which uses the Bourbon library that we've just imported)
to render a @font-face style rule:
See, how easy it was! We've already used the import directive to pull in mixins
from an external file. It's a simple matter of downloading the relevant files from
the Internet and referencing these instead.
The hard part thoughif indeed it can be described as suchis the choice of library
to use with lots of examples out there; here are a few examples to try out:
Compass: http://compass-style.org/
Bourbon: http://bourbon.io/
Scut: http://davidtheclark.github.io/scut/
Breakpoint: http://breakpoint-sass.com/
Buttons: http://unicorn-ui.com/buttons/builder/
Saffron: http://colindresj.github.io/saffron/
Andy.scss: https://github.com/gillesbertaux/andy
Using a library will reduce the amount of work we need to do when building style
sheets. Simply dropping it in won't be enough though; it does require a little work
to incorporate the library. Here are a few tips that will help:
Don't try to convert everything in one go; it is not worth the trouble. The great
Pyramids weren't built in a day. Working with Sass, particularly in large sites,
should be an iterative process over time (with changes made in chunks).
The key to working with libraries is choice, choice, and choice. There are
dozens of libraries available; don't feel obliged to stay with one if it doesn't
work well for you.
Sass will compile all the mixins from a library into valid CSS. If the bulk of
the styles are not used, then consider either extracting those that are needed
into a new custom library or move to using a different library where more
styles will be used.
We're not limited to just using mixin libraries. There are lots of people who
have written single or multiple mixins that are not part of any library. It's
worth researching online to see what is available. We will use some of these
examples, such as those created by Sebastian Ekstrm, which are available
at http://zerosixthree.se/8-sass-mixins-you-must-have-in-yourtoolbox/.
Enough chatting. I feel a couple of demos coming! It's time to put something of
what we've discussed into practice; to get a feel of what is involved, let's first use the
Animate.scss library (available at https://github.com/geoffgraham/animate.
scss) to animate some simple buttons. It's not going to win any awards for sure,
but it still shows the process involved in switching to using external libraries as our
mixin source.
Chapter 2
For this reason, mixins should concentrate more on the values required for an
animation to work and less on vendor prefixes. An ideal use for mixins is to
provide support for keyframe-based mixins, which require a few lines.
Let's dig in and take a look at how to animate content using Sass. We will use the
Sass version of Animate.scss created by Geoff Graham at https://github.com/
geoffgraham/animate.scss.
If desired, this can be installed using Bower. Look inside
bower.json for details of the name to use when installing.
Found in...
4. Save all of these in the _partials subfolder that sits within the sass folder.
[ 57 ]
5. We need to switch to using the mixins from the library. So, go ahead and
remove lines 1 to 59, replacing them with this:
@import "_partials/_properties.scss";
@import "_partials/_fadeOut.scss";
@import "_partials/_flipOutX.scss";
@import "_partials/_slideOutUp.scss";
.flipOutX {
@include flipOutX();
}
.fadeOut {
@include fadeOut();
}
.slideOutUp {
@include slideOutUp();
}
[ 58 ]
Chapter 2
We could easily just use any of the mixins in the library. While it is a perfectly usable
library in its own right, it only touches on a small part of what is possible. To give a
small flavor of what can be done, try visiting these three sites:
writing. It is a perfect work area to create our own animations. The code is
automatically generated as standard CSS, but with a little work, it can be
converted to Sass.
The key message here is that it is worth spending time when working with
something such as animation mixins. First, it is key to get your head around how
animation mixins work in Sass and then explore some of the options available in
terms of animations that we can use.
Let's move on and take a look at a different library. We will use similar principles in
the next demo, but this time, we will use the Compass library, which is frequently
used with Sass.
[ 59 ]
For this demo, we will use the Fira Sans font from http://www.
fontsquirrel.com/fonts/fira-sans; versions suitable for use
online have been created with the web font generator at http://www.
fontsquirrel.com/tools/webfont-generator.
For now, let's get stuck in. We'll start by installing Bourbon; this demo assumes that
Bower is already installed. Perform the following steps:
1. Let's start by making sure that the Koala application that we met back in
Chapter 1, Introducing Sass, is installed. If you don't have it running, refer
back to it for more details.
2. Next, bring up a Node prompt and change the current folder to our project
area. At this prompt, enter the following command and then press Enter:
bower install bourbon
3. If all is well, we should see this appear in the command prompt window:
[ 60 ]
Chapter 2
9. Hold on. This has thrown an error and is not compiled. To fix this, we need
to switch to using Koala. We will explore more of this error at the end of
the exercise.
[ 61 ]
10. Drag the sass folder on to the main window. This will add it as a project that
Koala can compile. Right-click on demopage-import.scss to compile, as
shown in this screenshot:
11. If all is well, we should see something akin to this screenshot when
previewing the results in a browser:
[ 62 ]
Chapter 2
At this point, we now have a working page that uses the @font-face mixin
excepthold onhasn't the font changed from the previous demo?
Absolutely! With a good reason: the font we used in the original demo is provided
using Google Fonts. Licensing issues mean that we can't download the font source
files and convert it to use the @font-face mixin. This means that we must use an
alternative font, such as Fira Sans, which we can download and import using the
@font-face mixin.
You may also spot that the quality of the font rendered on screen could look better.
This is not because I've chosen a bad font; some fonts are just not rendered well on
screen in a browser. To get around this, we can use the min-device-pixel-ratio
attribute to change the number of device pixels shown per CSS pixel. Alter the Sass
code as follows:
@media screen and (min-device-pixel-ratio: 0) {
@include font-face("fira_sansregular", "../fonts/firasansregular-webfont");
}
Then, recompile it, and all should be well. Hopefully, it will look a lot more like the
screenshot shown at the end of the exercise.
Summary
Mixins and variables are two of the most important parts of Sass; without them, our
options become somewhat limited. Let's take a moment to consolidate what you
have learned throughout this chapter.
We kicked off our journey with a look at how to use variables. Then, we looked at
how to assign numeric or alpha values, followed by how to store color values.
We then moved on to look at how Sass allows you to split your style sheet across
several files; we can use this to better structure our code and make each constituent
file more manageable.
Next, we discussed how to create mixins. We first touched on standard mixins before
altering them to become more dynamic and useful by passing values to each mixin.
We also covered how to use @extend with a pointer and how this can help dry out
our mixins and remove unnecessary code bloat.
[ 63 ]
We then rounded out our journey with a look at how to use external mixins from
prebuilt libraries, such as Compass or Bourbon, before diving into two examples that
used completely different libraries, yet demonstrated that the principals involved are
still the same.
Onwards we go! How many times have you had to write style rules that duplicate
(in whole or in part) selector names already in the style sheet? It's a real painnot
any more with Sass! Sass has a great facility that allows you to nest styles. I'll explain
more in the next chapter.
[ 64 ]
www.PacktPub.com
Stay Connected: