Variables in CSS with Sass

When you use Sass to write your CSS you gain a pretty powerful toolset. The first tool that you should become familiar with are variables. You may already be using variables in another language like JavaScript or PHP, or really any programming language and found yourself wondering why you can’t have such a simple and powerful tool in CSS as well. Thanks Sass.

Variables can be used to store any value in Sass. Let’s start with hexadecimal color values. Here I set up some basic color values using Sass in the Kit.

$darkgray: #a9a9a9
$lightgray: #d3d3d3
$red: #b80000

$base-color: $darkgray
$alt-color: $red
$background-color: $lightgray

body: 
  background-color: $background-color
  color: $base-color
  a
    color: $alt-color

Using these variables saves the trouble and time I used to spend forgetting, looking up, and creating pseudo “tables of contents” in my CSS files just to keep track of colors. Sass comes with some powerful color functions that let you do things like alter the opacity, lightness, hue, and saturation of any color.

$darkgray: scale-color($black, $lightness: 10%)
$lightgray: scale-color($white, $lightness: -10%)
$red: #b80000
$red-dark: scale-color($red, $lightness: -20%)

$base-color: $darkgray
$alt-color: $red
$background-color: $lightgray

body: 
  background-color: $background-color
  color: $base-color
  a
    color: $alt-color

Of course you can use variables to store numerical and string values as well. Sass is even smart enough to know if a variable is made of pixels, ems, or percents. Sass can perform some smart math on variables of different numerical types. My favorite use of string variables is to save font stacks as an easy to remember short name.

// font stacks
$font-sans: sans-serif
$font-serifs: Georgia, serif

// Dimensions
$kit-baseline: 24px
$kit-baseline-half: $kit-baseline * 0.5
$kit-baseline-neg: $kit-baseline * -1
$kit-gutter: 24px
$kit-gutter-half: $kit-gutter * 0.5 
$kit-gutter-neg: $kit-gutter * -1

In the example in the video I show how to combine these techniques using the Kit to quickly comp a web page prototype. check out the source code and example page here to try it yourself.

Posted on Sunday, July 10th, 2011