HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 139 posts at DZone. You can read more from them at their website. View Full User Profile

Dynamically Create CSS Classes With SASS

07.04.2014
| 9039 views |
  • submit to reddit

There are many advantages to using CSS pre-processors like SASS, some of the features allow you to end up writing less CSS code by using inheritance and functions in SASS to reuse the same code on your different CSS classes and IDs.

To learn more about getting started with SASS you can refer to a previous articles.

Getting started with SASS

One of my favourite features of SASS is the ability to use loops to dynamically create your CSS classes. A good example of this is when you want to make a set of classes to use for changing the text colours and background colours of elements you would normally have to write CSS like this.

.red-background {
  background: #FF0000;
}

.red-color {
  color: #FF0000;
}

.blue-background {
  background: #001EFF;
}

.blue-color {
  color: #001EFF;
}

.green-background {
  background: #00FF00;
}

.green-color {
  color: #00FF00;
}

.yellow-background {
  background: #F6FF00;
}

.yellow-color {
  color: #F6FF00;
}

If you want to add additional colours to this later you will have to remember to write both background and colour classes. With SASS we can create a list of our colours and then loop through these to create the CSS classes.

To create a list in SASS all you have to do is create a comma separated list of key value pairs like the following.

$colours:
  "red" #FF0000,
  "blue" #001EFF,
  "green" #00FF00,
  "yellow" #F6FF00;

Using the @each keyword in SASS we can loop through each of the colours and then use the nth() function to get the name of the class and the value of the class to dynamically create the classes in our CSS. The following each loop will generate exactly the same colour classes as above with only a few lines of code.

@each $i in $colours{
  .#{nth($i, 1)}-background {
    background: nth($i, 2);
  }
  .#{nth($i, 1)}-color {
    color:nth($i, 2);
  }
}
Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)