//

SASS – VARIABLES

Native CSS variable support is still in its infancy, but Sass affords us a way to set reusable values.

In Sass, Variable names begin with $, like $base.

style.scss

$base: #777777;

.sidebar {
    border: 1px solid $base;
    p {
        color: $base;
    }
}   

style.css

.sidebar {
    border: 1px solid #777777;
}
.sidebar p {
    color: #777777;
}

The Default Flag

Variable definitions can optionally take the !default flag:

style.scss

$title: 'My Blog';
$title: 'About Me'; // overrides the first value

h2:before {
    content: $title;
}

style.css

h2:before {
    content: 'About Me';
}

Let's resolve the above issue with the !default flag:

style.scss

$title: 'My Blog';
$title: 'About Me' !default;

h2:before {
    content: $title;
}

style.css

h2:before {
    content: 'My Blog';
}

Here at line 2, since a value exists, it isn't overwritten.

_buttons.scss

$rounded: 3px !default;

.btn-a {
    border-radius: $rounded;
    color: #777;
}
.btn-b {
    border-radius: $rounded;
    color: #222;
}

style.scss

$rounded: 5px;
@import "buttons";

Here, if a value hasn't defined elsewhere, it is used by default.

style.css

.btn-a {
border-radius: 5px;
    color: #777;
}

.btn-b {
border-radius: 5px;
    color: #222;
}

Variable Declaration + Use

Booleans

$rounded: false;
$shadow: true;

Numbers

Can be set with or without units:

$rounded: 4px;
$line-height: 1.5;
$font-size: 3rem;

Types

Colors

$base: purple;
$border: rgba(0, 255, 0, 0.5);
$shadow: #333;

Strings

Can be set with or without quotes:

$header: 'Helvetica Neue';
$callout: Arial;
$message: "Loading...";

Lists

$authors: nick, dan, aimee, drew;
$margin: 40px 0 20px 100px;

Null

$shadow: null;

Scope

style.scss

p {
    $border: #ccc;
    border-top: 1px solid $border;
}
h1 {
    border-top: 1px solid $border;
}

style.css

Syntax error: Undefined
variable: "$border"

Here border isn't available outside of its own block.

Reassignment in a Declaration

Variables set inside a declaration (within { }) aren't usable outside that block. Setting new values to variables set outside a declaration changes future instances.

style.scss

$color-base: #777777;
.sidebar {
    $color-base: #222222;
    background: $color-base;
}
p {
    color: $color-base;
}

style.css

.sidebar {
    background: #222222;
}
p {
    color: #222222;
}

As the highlighted line above, overwriting a variable in a declaration is global.

Use the Ruby-esque #{$variable} to shim variables into selectors, property names, and strings:

style.scss

$side: top;

sup {
    position: relative;
    #{$side}: -0.5em;
}
.callout-#{$side} {
    background: #777;
}

style.css

sup {
    position: relative;
    top: -0.5em;
}
.callout-top {
    background: #777;
}