Vincent Panugaling
Vincent Panugaling

Reputation: 906

Loop margin offsets using sass @each or @for control directives

I'm kind of new in sass, and as I'm practicing it I've encountered this situation.

How can I achieve list of margin-top, margin-right, margin-bottom and margin-left, with different value offsets(I know this may sound unclear).

So here is the output(supposed to be) of the generated .css file by .scss

.offset-top-1{
    margin-top: 1rem;
}
.offset-top-2{
    margin-top: 2rem;
}
.offset-top-3{
    margin-top: 3rem;
}
//.... so on to .offset-top-6 and also for .offset-right-x, .offset-bottom-x, and .offset-left-x

And here is my .scss file

    @mixin offset-margin($margins){
        margin: $margins;
    }

    @for $i from 1 through 20 {
        .offset-top-#{$i}{
            @include offset-margin(1rem * $i 0rem 0rem 0rem); // the other offset values should be removed since I'm dealing only for margin-top
        }
        .offset-right-#{$i}{
            @include offset-margin( 0rem 1rem * $i 0rem 0rem);
        }
        .offset-bottom-#{$i}{
            @include offset-margin(0rem 0rem 1rem * $i 0rem);
        }
        .offset-left-#{$i}{
            @include offset-margin( 0rem 0rem 0rem 1rem * $i);
        }
    }

EDIT:

the @mixin directive offset-margin only allows "margin" though, what I wanted to achieve is to have specific margin location e.g margin-right, margin-left, etc.

Upvotes: 2

Views: 3358

Answers (3)

zrowork
zrowork

Reputation: 60

Also another solution. The first one to generate margin and padding shorthands. The second one for margin and padding values.

// margin and padding i.e: m-1 = margin: 1px; p-1 = padding: 1px;
@each $abbr, $name in ('m': 'margin', 'p': 'padding') {
  @for $i from 1 through 100 {
    .#{$abbr}-#{$i} {
      #{$name}: 1px * $i;
    }
  }
}

// margin and paddings in separate directions i.e: mt-1 = margin-top: 1px; pb-1 = padding-bottom: 1px;
@each $abbr, $name in ('t': 'top', 'r': 'right', 'b': 'bottom', 'l': 'left') {
  @each $prop, $prop-name in ('m': 'margin', 'p': 'padding') {
    @for $i from 1 through 100 {
      .#{$prop}#{$abbr}-#{$i} {
        #{$prop-name}-#{$name}: 1px * $i;
      }
    }
  }
}

Upvotes: 0

Alpha Centorus
Alpha Centorus

Reputation: 1

You can also use map:

@each $abbr, $name in ("t": "top", "r": "right", "b": "bottom", "l": "left") {
    @for $i from 1 through 20 {
        .m#{$abbr}-#{$i} {
            margin-#{$name}: 1rem * $i;
        }
    }
}

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

try this code (tested on http://sassmeister.com/)

@mixin offset-margin($margin, $value){
  margin-#{$margin}: $value;
}

@for $i from 1 through 20 {
  @each $margin in top, left, bottom, right {

    .offset-#{$margin}-#{$i}{
      @include offset-margin($margin, 1rem * $i) 
    }

  }
}

Upvotes: 5

Related Questions