Sass Snippets - the Each Loop

August 5, 2013

Reading the Sass reference (and working at Viget) has made me realize how freaking powerful/awesome this pre-processor is, so I’d like to share small discoveries with you guys (aka just some little snippets to make coding more enjoyable :D).

Introducing Sass Snippets — a new weekly blog segment about how fucking cool Sass/Compass are.

The each loop is amazing. It’s used for targeting items in a given list. Some great use cases could be for staff profiles, social media icons, special buttons or text spans; really any set of items with similar characteristics and slight, significant alterations would work great with this method. I’m going to show an example for changing just the background-image on a set of social media icons.

First, define a list like so:

SCSS:

$social: twitter, facebook, instagram;

Here, we have a list called social with different networks as list items. We can now loop through each defined item by using the @each directive. What I did was name each of the icon images by the name of the network in the list (i.e. facebook.svg) as well as the specific class for that item (class = “social-icon facebook”). So what we’re doing here is, inside of the “social-icon” class, we’re looping through each item in the $social list, and for each class with the title of the list item (i.e. the social network), we’re setting it’s background-image to the name-of-the-network.svg.

SCSS:

.social-icon {
     // shared information here
     background: 50% no-repeat;
     background-size: 100%;
     float: left;
     height: 50px;
     width: 50px;
   
     // unique information loops here
     @each $network in $social {
          &.#{$network} {
               background-image: image-url("app_assets/social_icons/#{$network}.svg");
          }
     }
}

CSS produced by the each loop:

.social-icon.twitter {
  background-image: url("/images/app_assets/social_icons/twitter.svg");
}
 
.social-icon.facebook {
  background-image: url("/images/app_assets/social_icons/facebook.svg");
}
 
.social-icon.instagram {
  background-image: url("/images/app_assets/social_icons/instagram.svg");
}



TL;DR: define a sass list, then use @each to address each item in the list.

More Resources: