Dmitry GaIduk Dmitry GaIduk - 1 year ago 94
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.


Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download