Ashil John
Ashil John

Reputation: 7742

Generating column classes with dynamic width using SASS

I was trying to generate a dynamic grid system using SASS with variable widths using a @for loop. So far I have :

@for $value from 1 through 12 {

  $width: percentage(1/$value);

  .col-md-#{$value} {
    width: $width;
  }
}

The output for the above code would be:

.col-md-1 {
  width: 100%;
}

.col-md-2 {
  width: 50%;
}

.
.
.

.col-md-11 {
  width: 9.09091%;
}

.col-md-12 {
  width: 8.33333%;
}

Is there anyway this could be reversed by tinkering with the percentage functions in such a way that:

.col-md-12 {
  width: 100%;
}

and

.col-md-1 {
  width: 8.33333%;
}

The opposite of what I currently have. Thanks in advance.

Upvotes: 1

Views: 2187

Answers (1)

Brett DeWoody
Brett DeWoody

Reputation: 62743

A simple change to the math should do the trick:

@for $value from 1 through 12 {

  $width: percentage($value/12);

  .col-md-#{$value} {
    width: $width;
  }
}

results in:

.col-md-1 {
  width: 8.33333%;
}

.col-md-2 {
  width: 16.66667%;
}

.col-md-3 {
  width: 25%;
}

.col-md-4 {
  width: 33.33333%;
}

.col-md-5 {
  width: 41.66667%;
}

.col-md-6 {
  width: 50%;
}

.col-md-7 {
  width: 58.33333%;
}

.col-md-8 {
  width: 66.66667%;
}

.col-md-9 {
  width: 75%;
}

.col-md-10 {
  width: 83.33333%;
}

.col-md-11 {
  width: 91.66667%;
}

.col-md-12 {
  width: 100%;
}

Upvotes: 4

Related Questions