Dmitry GaIduk Dmitry GaIduk - 4 months ago 23
CSS Question

SaSS loops for usage

I would like to create classes, that apply specific margin to my blocks. For example:

.standard-margin-top {margin-top:10px;}
.standard-margin-bottom {margin-bottom: 10px;}
.small-margin-top {...}

...

.large-margin-left {...}


And so on. There are 20 classes together (each direction with
xs
,
small
,
standard
,
large
and
no
). Is it possible to simplify this with sass loops? I'm pretty new with it.

I've read, how to create loops with numbers but I have no idea, what should I do here.

Thanks!

Answer

Use @each loop.

There are two collections of sizes and margin directions: $sizes and $directions. Then we use @each loop to go through these collections and generate css selectors. Use #{} to insert variable value as string.

Demo on sassmeister

$sizes: xs, small, standard;
$directions: top, right, bottom, left;

@each $size in $sizes {
  @each $direction in $directions {
    .#{$size}-margin-#{$direction} {
      margin-#{$direction}: 10px;
    }
  }
}
Comments