Last Updated: February 25, 2016
·
1.333K
· andreacammarata

SASS Best Practice

If you need to create many different but similar styles, remember about the list data type and the @each rule.

Bad

.x-icon {

    width: 40px;
    height: 40px;
    background-size: contain;

    &.cat {
         background-image: url($icons-dir + '/cat.png');
    }
    &.dog {
         background-image: url($icons-dir + '/dog.png');
    }
    &.horse {
         background-image: url($icons-dir + '/horse.png');
    }
    &.pig {
         background-image: url($icons-dir + '/pig.png');
    }

}

Good

.x-icon {

    $icons: cat dog horse pig;
    $size: 40px;

    width: $size;
    height: $size;
    background-size: contain;

    @each $icon in $icons {
        &.#{$icon} {
            background-image: url($icons-dir + '/#{$icon}.png');
        }
    }

}

Where $icons-dir points to your icons resource folder and has been previously defined inside a shared _variables.scss file.