Sass for, each loop to generate css

Sass has some handy control directives that can be used to output css via some programming familiar syntax and constructs. I often like to have a multitude of margin and padding direction css that can be used as helper css classes that I can apply to html.

Here is a tidbit to do so in sass:

$directions: (
    top: top,
    right: right,
    bottom: bottom,
    left: left
);

$columns: 10;

@for $i from 1 through $columns {
    @each $key, $value in $directions {
        .m-#{$key}-#{(($columns) * $i)} {
            margin-#{$key}: (($columns) * $i) + px;
        }
        .p-#{$key}-#{(($columns) * $i)} {
            padding-#{$key}: (($columns) * $i) + px;
        }
    }
  
}

// this outputs as:
.m-top-10 {margin-left: 10px;}
.m-right-10 {margin-right: 10px;}
.m-bottom-10 {margin-bottom: 10px;}
.m-left-100 {margin-left: 10px;}

.p-top-10 {padding-left: 10px;}
.p-right-10 {padding-right: 10px;}
.p-bottom-10 {padding-bottom: 10px;}
.p-left-10 {padding-left: 10px;}

 // etc and so on until 100

Hope this helps




Random Posts