2

I'm writing a flexible Sass grid structure and I'm wanting to know if it's possible to generate variables from a loop in Sass.

Currently I have the following, which works for a 12 column grid:

$columns: 12;
$col-width: 100%/$columns;

$col-1: $col-width;
$col-2: $col-width*2;
$col-3: $col-width*3;
$col-4: $col-width*4;
$col-5: $col-width*5;
$col-6: $col-width*6;
$col-7: $col-width*7;
$col-8: $col-width*8;
$col-9: $col-width*9;
$col-10: $col-width*10;
$col-11: $col-width*11;
$col-12: $col-width*12; 

I would then apply the variables like so:

.sidebar {
    width: $col-4;
}

.main-col {
    width: $col-8;
}

However, if I wanted 10 column grid I'd need to manually go in a edit this each time. Not a huge amount of work but if I can use a loop to generate the variables for me it would be better.

Here's the ideal scenario:

$columns: 12;

@for $i from 1 through $columns {
   $col-#{$i}: ($i / $columns) * 100%;
}

I could then tweak the $columns variable according to my grid structure. I'm not 100% sure this even achievable using Sass. But it would be great if it was.

See a gist here for an example: http://www.sassmeister.com/gist/feecef8655dadd54f438e67e6c27dd0c

Any help would be gratefully recieved.

1 Answer 1

3

You need to use either @mixin or @function to achieve your goal.

@mixin example(http://sass-lang.com/documentation/file.SASS_REFERENCE.html#mixins):

$columns: 12;

@mixin col($num) {
  width:100% / $columns * $num;
}

.sidebar {
  @include col(4);
  float: left;
  background: red;
}

.main-col {
  @include col(8);
  float: left;
  background: blue;
}

@function example(http://sass-lang.com/documentation/file.SASS_REFERENCE.html#functions):

$columns: 12;    

@function col($num) {
  @return 100% / $columns * $num;;
}

.sidebar {
  width: col(4);
  float: left;
  background: red;
}

.main-col {
  width: col(8);
  float: left;
  background: blue;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.