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

Creating Functions and Operations

Save for later
  • 18 min read
  • 10 Aug 2015

article-image

In this article by Alex Libby, author of the book Sass Essentials, we will learn how to use operators or functions to construct a whole site theme from just a handful of colors, or defining font sizes for the entire site from a single value. You will learn how to do all these things in this article.

Okay, so let's get started!

(For more resources related to this topic, see here.)

Creating values using functions and operators

Imagine a scenario where you're creating a masterpiece that has taken days to put together, with a stunning choice of colors that has taken almost as long as the building of the project and yet, the client isn't happy with the color choice. What to do? At this point, I'm sure that while you're all smiles to the customer, you'd be quietly cursing the amount of work they've just landed you with, this late on a Friday. Sound familiar? I'll bet you scrap the colors and go back to poring over lots of color combinations, right? It'll work, but it will surely take a lot more time and effort.

There's a better way to achieve this; instead of creating or choosing lots of different colors, we only need to choose one and create all of the others automatically. How? Easy! When working with Sass, we can use a little bit of simple math to build our color palette.

One of the key tenets of Sass is its ability to work out values dynamically, using nothing more than a little simple math; we could define font sizes from H1 to H6 automatically, create new shades of colors, or even work out the right percentages to use when creating responsive sites! We will take a look at each of these examples throughout the article, but for now, let's focus on the principles of creating our colors using Sass.

Creating colors using functions

We can use simple math and functions to create just about any type of value, but colors are where these two really come into their own.

The great thing about Sass is that we can work out the hex value for just about any color we want to, from a limited range of colors. This can easily be done using techniques such as adding two values together, or subtracting one value from another.

To get a feel of how the color operators work, head over to the official documentation at http://sass-lang.com/documentation/file.SASS_REFERENCE.html#color_operations—it is worth reading!

Nothing wrong with adding or subtracting values—it's a perfectly valid option, and will result in a valid hex code when compiled. But would you know that both values are actually deep shades of blue? Therein lies the benefit of using functions; instead of using math operators, we can simply say this:

p {
color: darken(#010203, 10%);
}

This, I am sure you will agree, is easier to understand as well as being infinitely more readable!

The use of functions opens up a world of opportunities for us. We can use any one of the array of functions such as lighten(), darken(), mix(), or adjust-hue() to get a feel of how easy it is to get the values. If we head over to http://jackiebalzer.com/color, we can see that the author has exploded a number of Sass (and Compass—we will use this later) functions, so we can see what colors are displayed, along with their numerical values, as soon as we change the initial two values.

Okay, we could play with the site ad infinitum, but I feel a demo coming on—to explore the effects of using the color functions to generate new colors. Let's construct a simple demo. For this exercise, we will dig up a copy of the colorvariables demo and modify it so that we're only assigning one color variable, not six.

For this exercise, I will assume you are using Koala to compile the code.

Okay, let's make a start:

  1. We'll start with opening up a copy of colorvariables.scss in your favorite text editor and removing lines 1 to 15 from the start of the file.
  2. Next, add the following lines, so that we should be left with this at the start of the file:
    $darkRed: #a43;
    $white: #fff;
    $black: #000;
     
    $colorBox1: $darkRed;
    $colorBox2: lighten($darkRed, 30%);
    $colorBox3: adjust-hue($darkRed, 35%);
    $colorBox4: complement($darkRed);
    $colorBox5: saturate($darkRed, 30%);
    $colorBox6: adjust-color($darkRed, $green: 25);
  3. Save the file as colorfunctions.scss. We need a copy of the markup file to go with this code, so go ahead and extract a copy of colorvariables.html from the code download, saving it as colorfunctions.html in the root of our project area. Don't forget to change the link for the CSS file within to colorfunctions.css!
  4. Fire up Koala, then drag and drop colorfunctions.scss from our project area over the main part of the application window to add it to the list:

    creating-functions-and-operations-img-0

  5. Right-click on the file name and select Compile, and then wait for it to show Success in a green information box.
  6. If we preview the results of our work in a browser, we should see the following boxes appear:

    creating-functions-and-operations-img-1

At this point, we have a working set of colors—granted, we might have to work a little on making sure that they all work together. But the key point here is that we have only specified one color, and that the others are all calculated automatically through Sass.

Now that we are only defining one color by default, how easy is it to change the colors in our code? Well, it is a cinch to do so. Let's try it out using the help of the SassMeister playground.

Changing the colors in use

We can easily change the values used in the code, and continue to refresh the browser after each change. However, this isn't a quick way to figure out which colors work; to get a quicker response, there is an easier way: use the online Sass playground at http://www.sassmeister.com.

This is the perfect way to try out different colors—the site automatically recompiles the code and updates the result as soon as we make a change. Try copying the HTML and SCSS code into the play area to view the result. The following screenshot shows the same code used in our demo, ready for us to try using different calculations:

creating-functions-and-operations-img-2

All images work on the principle that we take a base color (in this case, $dark-blue, or #a43), then adjust the color either by a percentage or a numeric value. When compiled, Sass calculates what the new value should be and uses this in the CSS. Take, for example, the color used for #box6, which is a dark orange with a brown tone, as shown in this screenshot:

creating-functions-and-operations-img-3

To get a feel of some of the functions that we can use to create new colors (or shades of existing colors), take a look at the main documentation at http://sass-lang.com/documentation/Sass/Script/Functions.html, or https://www.makerscabin.com/web/sass/learn/colors. These sites list a variety of different functions that we can use to create our masterpiece.

We can also extend the functions that we have in Sass with the help of custom functions, such as the toolbox available at https://github.com/at-import/color-schemer—this may be worth a look.

In our demo, we used a dark red color as our base. If we're ever stuck for ideas on colors, or want to get the right HEX, RGB(A), or even HSL(A) codes, then there are dozens of sites online that will give us these values. Here are a couple of them that you can try:

Mixing colors

The one thing that we've not discussed, but is equally useful is that we are not limited to using functions on their own; we can mix and match any number of functions to produce our colors.

A great way to choose colors, and get the appropriate blend of functions to use, is at http://sassme.arc90.com/. Using the available sliders, we can choose our color, and get the appropriate functions to use in our Sass code. The following image shows how:

creating-functions-and-operations-img-4

In most cases, we will likely only need to use two functions (a mix of darken and adjust hue, for example); if we are using more than two–three functions, then we should perhaps rethink our approach! In this case, a better alternative is to use Sass's mix() function, as follows:

$white: #fff;
$berry: hsl(267, 100%, 35%);
p { mix($white, $berry, 0.7) }

…which will give the following valid CSS:

p {
color: #5101b3;
}

This is a useful alternative to use in place of the command we've just touched on; after all, would you understand what adjust_hue(desaturate(darken(#db4e29, 2), 41), 67) would give as a color? Granted, it is something of an extreme calculation, nonetheless, it is technically valid. If we use mix() instead, it matches more closely to what we might do, for example, when mixing paint. After all, how else would we lighten its color, if not by adding a light-colored paint?

Okay, let's move on. What's next? I hear you ask. Well, so far we've used core Sass for all our functions, but it's time to go a little further afield. Let's take a look at how you can use external libraries to add extra functionality. In our next demo, we're going to introduce using Compass, which you will often see being used with Sass.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at ₹800/month. Cancel anytime

Using an external library

So far, we've looked at using core Sass functions to produce our colors—nothing wrong with this; the question is, can we take things a step further?

Absolutely, once we've gained some experience with using these functions, we can introduce custom functions (or helpers) that expand what we can do. A great library for this purpose is Compass, available at http://www.compass-style.org; we'll make use of this to change the colors which we created from our earlier boxes demo, in the section, Creating colors using functions.

Compass is a CSS authoring framework, which provides extra mixins and reusable patterns to add extra functionality to Sass. In our demo, we're using shade(), which is one of the several color helpers provided by the Compass library.

Let's make a start:

  1. We're using Compass in this demo, so we'll begin with installing the library. To do this, fire up Command Prompt, then navigate to our project area.
  2. We need to make sure that our installation RubyGems system software is up to date, so at Command Prompt, enter the following, and then press Enter:
    gem update --system
  3. Next, we're installing Compass itself—at the prompt, enter this command, and then press Enter:
    gem install compass
  4. Compass works best when we get it to create a project shell (or template) for us. To do this, first browse to http://www.compass-style.org/install, and then enter the following in the Tell us about your project… area:

    creating-functions-and-operations-img-5

    Leave anything in grey text as blank.

  5. This produces the following commands—enter each at Command Prompt, pressing Enter each time:

    creating-functions-and-operations-img-6

  6. Navigate back to Command Prompt. We need to compile our SCSS code, so go ahead and enter this command at the prompt (or copy and paste it), then press Enter:
    compass watch –sourcemap
  7. Next, extract a copy of the colorlibrary folder from the code download, and save it to the project area.
  8. In colorlibrary.scss, comment out the existing line for $backgrd_box6_color, and add the following immediately below it:
    $backgrd_box6_color: shade($backgrd_box5_color, 25%);
  9. Save the changes to colorlibrary.scss. If all is well, Compass's watch facility should kick in and recompile the code automatically. To verify that this has been done, look in the css subfolder of the colorlibrary folder, and you should see both the compiled CSS and the source map files present.

    If you find Compass compiles files in unexpected folders, then try using the following command to specify the source and destination folders when compiling:

    compass watch --sass-dir sass --css-dir css
  10. If all is well, we will see the boxes, when previewing the results in a browser window, as in the following image. Notice how Box 6 has gone a nice shade of deep red (if not almost brown)?

    creating-functions-and-operations-img-7

  11. To really confirm that all the changes have taken place as required, we can fire up a DOM inspector such as Firebug; a quick check confirms that the color has indeed changed:

    creating-functions-and-operations-img-8

  12. If we explore even further, we can see that the compiled code shows that the original line for Box 6 has been commented out, and that we're using the new function from the Compass helper library:

    creating-functions-and-operations-img-9

This is a great way to push the boundaries of what we can do when creating colors. To learn more about using the Compass helper functions, it's worth exploring the official documentation at http://compass-style.org/reference/compass/helpers/colors/. We used the shade() function in our code, which darkens the color used. There is a key difference to using something such as darken() to perform the same change. To get a feel of the difference, take a look at the article on the CreativeBloq website at http://www.creativebloq.com/css3/colour-theming-sass-and-compass-6135593, which explains the difference very well.

The documentation is a little lacking in terms of how to use the color helpers; the key is not to treat them as if they were normal mixins or functions, but to simply reference them in our code. To explore more on how to use these functions, take a look at the article by Antti Hiljá at http://clubmate.fi/how-to-use-the-compass-helper-functions/.

We can, of course, create mixins to create palettes—for a more complex example, take a look at http://www.zingdesign.com/how-to-generate-a-colour-palette-with-compass/ to understand how such a mixin can be created using Compass.

Okay, let's move on. So far, we've talked about using functions to manipulate colors; the flip side is that we are likely to use operators to manipulate values such as font sizes.

For now, let's change tack and take a look at creating new values for changing font sizes.

Changing font sizes using operators

We already talked about using functions to create practically any value.

Well, we've seen how to do it with colors; we can apply similar principles to creating font sizes too. In this case, we set a base font size (in the same way that we set a base color), and then simply increase or decrease font sizes as desired.

In this instance, we won't use functions, but instead, use standard math operators, such as add, subtract, or divide. When working with these operators, there are a couple of points to remember:

  • Sass math functions preserve units—this means we can't work on numbers with different units, such as adding a px value to a rem value, but can work with numbers that can be converted to the same format, such as inches to centimeters
  • If we multiply two values with the same units, then this will produce square units (that is, 10px * 10px == 100px * px). At the same time, px * px will throw an error as it is an invalid unit in CSS.
  • There are some quirks when working with / as a division operator —in most instances, it is normally used to separate two values, such as defining a pair of font size values. However, if the value is surrounded in parentheses, used as a part of another arithmetic expression, or is stored in a variable, then this will be treated as a division operator.

    For full details, it is worth reading the relevant section in the official documentation at http://sass-lang.com/documentation/file.Sass_REFERENCE.html#division-and-slash.

With these in mind, let's create a simple demo—a perfect use for Sass is to automatically work out sizes from H1 through to H6. We could just do this in a simple text editor, but this time, let's break with tradition and build our demo directly into a session on http://www.sassmeister.com. We can then play around with the values set, and see the effects of the changes immediately. If we're happy with the results of our work, we can copy the final version into a text editor and save them as standard SCSS (or CSS) files.

  1. Let's begin by browsing to http://www.sassmeister.com, and adding the following HTML markup window:
    <html>
    <head>
       <meta charset="utf-8" />
       <title>Demo: Assigning colors using variables</title>
       <link rel="stylesheet" type="text/css" href="css/     colorvariables.css">
    </head>
    <body>
       <h1>The cat sat on the mat</h1>
       <h2>The cat sat on the mat</h2>
       <h3>The cat sat on the mat</h3>
       <h4>The cat sat on the mat</h4>
       <h5>The cat sat on the mat</h5>
       <h6>The cat sat on the mat</h6>
    </body>
    </html>
    
  2. Next, add the following to the SCSS window—we first set a base value of 3.0, followed by a starting color of #b26d61, or a dark, moderate red:
    $baseSize: 3.0;
    $baseColor: #b26d61;

    We need to add our H1 to H6 styles. The rem mixin was created by Chris Coyier, at https://css-tricks.com/snippets/css/less-mixin-for-rem-font-sizing/.

  3. We first set the font size, followed by setting the font color, using either the base color set earlier, or a function to produce a different shade:
    h1 {
    font-size: $baseSize;
    color: $baseColor;
    }
     
    h2 {
    font-size: ($baseSize - 0.2);
    color: darken($baseColor, 20%);
    }
     
    h3 {
    font-size: ($baseSize - 0.4);
    color: lighten($baseColor, 10%);
    }
     
    h4 {
    font-size: ($baseSize - 0.6);
    color: saturate($baseColor, 20%);
    }
     
    h5 {
    font-size: ($baseSize - 0.8);
    color: $baseColor - 111;
    }
     
    h6 {
    font-size: ($baseSize - 1.0);
    color: rgb(red($baseColor) + 10, 23, 145);
    }
  4. SassMeister will automatically compile the code to produce a valid CSS, as shown in this screenshot:

    creating-functions-and-operations-img-10

Try changing the base size of 3.0 to a different value—using http://www.sassmeister.com, we can instantly see how this affects the overall size of each H value. Note how we're multiplying the base variable by 10 to set the pixel value, or simply using the value passed to render each heading.

In each instance, we can concatenate the appropriate unit using a plus (+) symbol. We then subtract an increasing value from $baseSize, before using this value as the font size for the relevant H value.

You can see a similar example of this by Andy Baudoin as a CodePen, at http://codepen.io/baudoin/pen/HdliD/. He makes good use of nesting to display the color and strength of shade. Note that it uses a little JavaScript to add the text of the color that each line represents, and can be ignored; it does not affect the Sass used in the demo.

The great thing about using a site such SassMeister is that we can play around with values and immediately see the results.

For more details on using number operations in Sass, browse to the official documentation, which is at http://sass-lang.com/documentation/file.Sass_REFERENCE.html#number_operations.

Okay, onwards we go. Let's turn our attention to creating something a little more substantial; we're going to create a complete site theme using the power of Sass and a few simple calculations.

Summary

Phew! What a tour! One of the key concepts of Sass is the use of functions and operators to create values, so let's take a moment to recap what we have covered throughout this article.

We kicked off with a look at creating color values using functions, before discovering how we can mix and match different functions to create different shades, or using external libraries to add extra functionality to Sass.

We then moved on to take a look at another key use of functions, with a look at defining different font sizes, using standard math operators.

Resources for Article:


Further resources on this subject: