How to use Sass to make easily scalable styles

Nowadays frontend developers can't live without some preprocess tool that make tackling the CSS style easier.

In Ymbra we prefer Sass (Syntactically Awesome StyleSheets) in the themes of our projects, and often we opted to develop subthemes of Zen, and take advantage of all the tools and benefits that gives us regarding writing the CSS style of the project.

I would like to explain how Sass can help us, a lot, to improve the process of one task specifically: generate the CSS of a project which have a common style for all the elements, with some color and tone variants defined by a increase number of skins or variations.

As a real example we can imagine a page that show different background and anchor colors depending on the user selection. If we assume that user's choice becomes a class inside the tag body, we only need to have some different selectors with properties that change depending on the applied style for that user.

The Sass code resultant to define three different styles could be something like:

// Golden style colors.
.style-golden {
  background-color: #ff0;
  a {
    color: #f00;
  }
}
// Dark style colors.
.style-dark {
  background-color: #000;
  a {
    color: #ccc;
  }
}
// Pony style colors.
.style-pony {
  background-color: #f0f;
  a {
    color: #505;
  }
}

Where style-golden, style-dark and style-pony are the style names chosen by the user and the class added to the body element.

Using this solution, as may have already tought, we'll have to rewrite all the lines again for each new style that we want to add in the future, becoming very hard to maintain.

To build a more scalable solution without having to repeat a lot of code, Sass allows us to store the selectors and the value of the different colors in list variables, and later do a foreach to iterate and assign the values of each styles.

The Sass code would be:

// Define the list variables.
$styles: 'golden', 'dark', 'pony';
$body_colors: #ff0, #000, #f0f;
$anchor_colors: #f00, #ccc, #505;

// Initialize a counter variable.
$i: 1;

/* Iterate an list variable
  and apply the lis values to the CSS properties. */
@each $style in $styles {
  .style-#{$style} {
    background-color: nth($body_colors, $i);
    a {
      color: nth($anchor_colors, $i);
    }
  }
  // Increase the count variable.
  $i: $i + 1;
}

So we could add all the styles we wanted modifying only the stored values in the list variables, making our resultant code more maintainable.