Hashrocket.com / blog

Bg default article large

SASS Iteration using @each

posted on and written by Shane Riley in

Image 100x100 shane riley

If you're writing SASS, you should be taking advantage of the @each iterator to handle minor changes in styles between elements that share common styles. The syntax is very easy to pick up, with the only stumbling point (for me, anyways) being that the collection to be iterated over is not contained in an array-like object (like []) and the elements of the collection are not encapsulated in quotes.

Let's jump right in to an example. Say you have a list of social media links you need to style. You have equal size icons for Twitter, Facebook, GitHub, etc. You've cut them all into a sprite map. Now you need to write out the styles for each class to change the background position. What you'd do to output these classes and associated positions is something like this:

ul.social_media
  li
    padding: 5px 10px
    a
      display: block
      padding: 0 0 0 21px
      background: transparent url("icon_social-media.png") 5px 0 no-repeat
      // Set your initial y-position
      $i: 0
    @each $icon in twitter, facebook, github
      &.#{$icon}
        a
          background-position: 5px $i
        $i: $i - 16px

This makes adding more icons much easier. All you need to do is add the icon to the bottom of the sprite sheet and add the class name to the end of our collection being iterated over.

SASS also has for and while loops that you can take advantage of. Check out the SASS reference for more info on this and the other control directives.

Posted in Design and tagged with CSS