cmp
cmp

Reputation: 452

CSS margin loop incrementing by X amount each time

I wonder if it is possible to do this with SCSS? Incrementing by X each time.

It is tricky because the -s or -md needs to be updated instead of the number.

  @for $i from 1 through 6 {
      .u-marg-t-#{$i} {
        margin-top: 0px + ($i * 8);
      }
    } 

Aside from this not even counting correctly, is a @for the best approach, here?

Plain CSS output

.u-marg-t {
    &-xs {
        margin-top: 8px;
    }

    &-sm {
        margin-top: 16px;
    }

    &-md {
        margin-top: 24px;
    }

    &-lg {
        margin-top: 32px;
    }

    &-xl {
        margin-top: 43px;
    }

    &-xxl {
        margin-top: 50px;
    }
}

.u-marg-b {
    &-xs {
        margin-bottom: 8px;
    }

    &-sm {
        margin-bottom: 16px;
    }

    &-md {
        margin-bottom: 24px;
    }

    &-lg {
        margin-bottom: 32px;
    }

    &-xl {
        margin-bottom: 43px;
    }

    &-xxl {
        margin-bottom: 50px;
    }
}

Upvotes: 0

Views: 88

Answers (1)

Pedro Vitorino
Pedro Vitorino

Reputation: 46

You could use a list with the suffixes you want to use and iterate through inside your for loop. Here's an example:

$sizes: xs, sm, md, lg, xl, xxl;

@for $i from 1 through 6 {
    .u-marg-t-{
        &#{nth($sizes, $i)} {
            margin-top: 0px + ($i * 8);
        }
    }
}

$sizes is your list with the suffixes. Inside the loop I used the function nth($list, $i) to get the item at position $i in your list.

Upvotes: 1

Related Questions