Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Selectors inside of a loop using Sass

Tags:

loops

sass

The Issue

I'm currently in a pickle. I need to group selectors inside of a Sass loop. I've tried many different ways to go about doing this such as:

body {
    $store: null;
    @for $i from 1 through 10 {
        $store: append($store, ".offset-by-#{$i}", comma);
    }
    // produces content: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
    @each $j in $store {
        $store: unquote($j);
    }
    // produces .offset-by-10
}

What I'm trying to accomplish using pure Sass (no Ruby) is the following:

.offset-by-1,
.offset-by-2,
.offset-by-3,
...
.offset-by-10 { foo: bar; }

If you are a Sass god then please give me an idea of what to do here. If this is an inherent limitation of the meta-language then let me know about that too!

Considerations

I can't use anything other than a mixin to accomplish this because functions are expected to be used on a property value. Mixins, on the other hand allow the production of entire blocks of code.

like image 428
djthoms Avatar asked Jul 09 '13 22:07

djthoms


2 Answers

Keep it simple, soldier!

%foo {
  foo: bar; }

@for $i from 1 through 10 {
  .offset-by-#{$i} {
    @extend %foo; }}

UPD You can also have individual styles with this approach:

%foo {
  foo: bar; }

@for $i from 1 through 10 {
  .offset-by-#{$i} {
    @extend %foo;
    margin-left: 50px * $i; }}

Which results in the following CSS:

.offset-by-1, .offset-by-2, .offset-by-3, .offset-by-4, .offset-by-5, .offset-by-6, .offset-by-7, .offset-by-8, .offset-by-9, .offset-by-10 {
  foo: bar; }

.offset-by-1 {
  margin-left: 50px; }

.offset-by-2 {
  margin-left: 100px; }

.offset-by-3 {
  margin-left: 150px; }

.offset-by-4 {
  margin-left: 200px; }

.offset-by-5 {
  margin-left: 250px; }

.offset-by-6 {
  margin-left: 300px; }

.offset-by-7 {
  margin-left: 350px; }

.offset-by-8 {
  margin-left: 400px; }

.offset-by-9 {
  margin-left: 450px; }

.offset-by-10 {
  margin-left: 500px; }
like image 184
Andrey Mikhaylov - lolmaus Avatar answered Sep 29 '22 13:09

Andrey Mikhaylov - lolmaus


Have you tried something like this:

@mixin createNumbered($num, $className){
    @for $i from 1 through $num {
        .#{$className}-#{$i} {
            @content;
        }
    }
}

@include createNumbered(10, 'foo-bar'){
    color: white;
}

Updated:

@mixin createNumbered($num, $className){
    $foo : '';
    @for $i from 1 through $num {
        $foo : $foo + '.' + $className + '-' + $i + ', ';
    }
    #{$foo} {
        @content;
    }
}

@include createNumbered(10, 'foo-bar'){
    color: white;
}
like image 41
Clark Pan Avatar answered Sep 29 '22 12:09

Clark Pan