Valerio Pierbattista
Front end web developer

Sass Maps A Simple Use Case

September 08, 2014

I just recently discovered and used Sass Maps, which are basically arrays of values which can be intelligently used to write less code in particular situations. This is just one use case that was useful for me and may be useful for you to understand the power of Sass Maps.

I wanted to achieve something like this:

Screenshot_1

That’s basically two div.box (I wanted more by the way, and more colors) with two different look&feel based on a particular color. You have a big .bar on top with a red background, an h1 and an a of that same red color. The next .box is based on the same scheme, but has a green color instead. What I didn’twant to do was writing endless css like


.box {
    &.color1 {
      .bar {background:red}
      h1 {color:red}
      a {color:red}
        }
    &.color2 {
      .bar {background:green}
      h1 {color:green}
      a {color:green}
      }
}

for every section. That’s when sass maps and sass control directives come in handy: all I want to do is reproduce that color scheme just by changing the class of the containing div.box and rely on a simple set of color managed by a sass map. That’s way more maintainable …

This is my html:


<div class="box color1">
<div class="bar">
	Some text here
</div>
<div class="text">
  <h1>This is a heading </h1>
  <h2>And this is a subtitle</h2>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit
amet quam egestas semper. Aenean ultricies mi vitae est. <a href="#">Mauris placerat eleifend</a> leo.</p>
</div>
</div>

this is the sass map:


$color-set: (
    color1: #03A9F4,
    color2: #FF5252,
    color3: #8BC34A
);

And this is the handy function that does the magic:

   
@each $color-class, $the-color in $color-set {
  .box.#{$color-class} {
    .bar {
      background: $the-color;
      &.darken{background:darken($the-color,5%)}
     } //bar

    h1, a {color:$the-color}

  } //box.#{color}
} //end of loop
    

You're all set, you can add or remove colors from the sass maps, and just add the appropriate class in the div.box, the function will then compile the appropriate style for every section based on the class assigned to the div.box.
You can see it in action here: Sass Maps Test on CodePen.

Share this:

Back

Guest Posts

Recent Posts