Looping Sass Arrays

Whilst I prefer a fluid approach to website building, occasionally something more rigid is required. In these happy times I turn to a handy technique using a few fudged Sass/SCSS associative arrays (technically multiple lists) to easily maintain those fiddly fixed-width menus.

Given some HTML hooks;

        <li class="home"><a href="/home">Home</a></li>
        <li class="about"><a href="/about">About</a></li>
        <li class="blog"><a href="/blog">Blog</a></li>
        <li class="contact"><a href="/contact">Contact</a></li>

We create our SCSS lists like so… (it's helpful to tab line everything up)

$nav_section: home about blog contact;
$nav_widths: 80 120 100 140;
$nav_colors: red yellow blue green;

Then using a loop with a counter to reference those different collections using nth(), we can set the width, change the colour, or nudge the background position of a sprite.

$bg_position: 0;

nav {
    li {
        @each $section in $nav_section {

            &.#{$section} a {
                width: nth($nav_widths, $i) + px;
                background-color: nth($nav_colors, $i);
                background-position: -$bg_position + px 0px;
            // add width to position counter
            $bg_position: $bg_position + nth($nav_widths, $i);

            $i: $i+1;

Producing the following CSS

nav li.home a {
  width: 80px;
  background-color: red;
  background-position: 0px 0px;
nav li.about a {
  width: 120px;
  background-color: yellow;
  background-position: -80px 0px;
nav li.blog a {
  width: 100px;
  background-color: blue;
  background-position: -200px 0px;
nav li.contact a {
  width: 140px;
  background-color: green;
  background-position: -300px 0px;

I've whacked this code in a gist for easy consumption;