Sass column sizes mixin

1.1k Views Asked by At

I'm writing a mixin to create a bunch of column size classes, this is the code I've got so far:

.col {
    @for $span from 1 through 12 {
        @for $total from 1 through 12 {
            @if $total > $span {
                &--#{$span}of#{$total} {
                    width: percentage($span/$total);
                }
            }
        }
    }
}

This outputs classes of .col--XofX, where x is each number between 1 and 12. This means my classes are coming out like these examples:

.col--1of1
.col--1of2
.col--1of3

Etc, all the way to 1of12.

I am also getting classes of:

.col--5of8
.col--7of10
.col--10of12

Etc, as long as the $span is a smaller number than the $total, again, up to 12.

What I'm wondering is if there is a better way of writing this mixin, such as passing in the 1 through 12 for each property, something like the below idea. Also I wouldn't want classes where the span is larger than the total, so I don't want `.col--8of1' etc.

$span: 1 through 12
$total: 1 through 12
@mixin create-cols($span, $total) {
    .col--#{$span}of#{$total} {}
}

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

If I understand correctly, you want only to include classes as they are needed, rather than print every permutation. Is something like this what you mean?

@mixin create-cols($span, $total) {
  .col--#{$span}-of-#{$total} {
    width: (($span/$total)*100%);
  }
}

.col {
  @include create-cols(2, 12);  
  @include create-cols(3, 12);
  @include create-cols(6, 12);  
}

Compiles to:

.col .col--2-of-12 {
  width: 16.66667%;
}
.col .col--3-of-12 {
  width: 25%;
}
.col .col--6-of-12 {
  width: 50%;
}

SASSMEISTER

Note that you may wish to introduce some rounding logic for the percentages, but that is a separate issue.