9Defining Variables

Have you ever been in a situation where you are copying the value of a color over and over again? That very specific blue that your clients want appears in so many places. Then, a couple of weeks later, they want you to change the color. Or—even worse—you have a whole lot of colors to change. Find and replace time! Color handling in CSS is not DRY (there’s that Don’t Repeat Yourself again!) at all.

Sass introduces variables to help us manage problems like this. All variables in Sass are prefixed with a $ sign. Assigning a variable looks a lot like typing in a CSS property. For instance, we can set the $primary_color variable by adding the super-simple line: $primary_color: #369;. That’s it!

To use the variable, we can just use the variable name where we’d usually use the property value. If we had to change the colors of the whole document, all we’d need to do is change the hex value of the variable and it’s sorted for us when the CSS compiles.

We can use variables to represent colors, sizes, percents, and several other things that are less commonly used. Anything that you can put to the right of a CSS property is easily understood by Sass.

Another neat thing about variables is they can be global or scoped. We’ve pretty much gone through global variables: They’re when a variable is defined on its own line, and they apply to the whole style sheet. Scoped variables, on the other hand, appear within a selector and will only apply to that selector and its children.

We can set default variables with the !default tag after assignment. When a variable is used, the default is used if there are no other assignments to that variable.

It’s pretty standard in a Sass document to declare the variables at the top of a file and use them throughout. If you’re familiar with C, then you’ll be familiar with using constants this way. Or if you have a large project, you might want to create a file that defines all of the variables. We’ll show you how you can break up your Sass files in Task 12, Importing.

What To Do...
  • Define and use variables.
    basics/variable_example.scss
     
    $​primary_color​: #369;
     
    $​secondary_color​: #eee;
     
    $​page_width​: 300px;
     
     
    body​ {
     
    // Set the background to be #369
     
    background: $primary_color;
     
    #wrapper {
     
    width: $page_width;
     
    background: white;
     
    border: $secondary_color;
     
    h1 {
     
    color: $primary_color; } } }

    This compiles to:

     
    body​ {
     
    background: #336699; }
     
    body​ #wrapper {
     
    width: 300px;
     
    background: white;
     
    border: #eeeeee; }
     
    body​ #wrapper ​h1​ {
     
    color: #336699; }

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.113.193