Last Updated: January 28, 2019
· chrisdl

Replace a SASS list with a SASS map

SASS has a new datatype (docs)

So let's say you have a button maker (a very simple one). The only thing it takes is a font size and a border radius.

To keep it scalable you might want to create a list of values and a mixin to set them.

$sizes: "small" 1px 1.2rem, "medium" 2px 1.6rem, "large" 3px 2rem

    @each $sizeVal in $sizes
        @if $size == "#{nth($sizeVal, 1)}"
            border-radius: nth($sizeVal, 2)
            font-size: nth($sizeVal, 3)

But now you can just create a map and get its values instead!

$sizes: (smallBorderRadius: 1px, smallFontSize: 1.2rem, mediumBorderRadius: 2px, mediumFontSize: 1.6rem, largeBorderRadius: 3px, largeFontSize: 2rem)

    border-radius: map-get($sizes, "#{$size}BorderRadius")
    font-size: map-get($sizes, "#{$size}FontSize")

This way you just have to feed in whatever you are calling the sizes, in this case small, medium and large. No more messy looping and @if statements!


I put together a third way of using a map with lists inside of it to keep it (subjectively) a bit cleaner. Check it out on sassmeister

or view the gist here

2 Responses
Add your response

Thanks Chris, this is very useful! I really like the clean way you've set it up in the gist, going to incorporate that in the project I'm working on :) Sass 3.3 is truly amazing!

over 1 year ago ·

Very welcome =)

over 1 year ago ·