0

I'm creating a bunch of heading styles using a @for loop but I can't get it to work with variable names, as in the following:

// Some variables (these work fine)
$h1-size: 3em;
$h2-size: 2em;
$h3-size: 1.6em;
etc...

// My loop
@for $i from 1 through 6 {
    h#{$i} {  
        color: #333;
        font-size: $h#{$i}-size; // DOESN'T WORK!
    } 
}

The loop works -- but only if i remove the part about font-size. Can I point at a dynamically constructed variable like this?

adam Kiryk
  • 1,735
  • 2
  • 14
  • 14

2 Answers2

3

You can't do this, and probably shouldn't. Good news: the upcoming 3.3 release will introduce a mapping type.

// Some variables (these work fine)
$header-info: (
    1: (size: 3em),
    2: (size: 2em),
    3: (size: 1.6em),
);

@for $i from 1 through 6 {
    h#{$i} {  
        color: #333;
        font-size: map-get(map-get($header-info, $i), size);
    } 
}
Eevee
  • 47,412
  • 11
  • 95
  • 127
0

I've looked into this a bunch and don't seem to find anything in the documentation that would support it. The best I can come up with is the following workaround:

// First, make sure you've got all your variables declared
$h1-size: 3em;
$h2-size: 2em;
etc...

// Then, make a list of the variable names
$sizelist: $h1-size $h2-size $h3-size $h4-size $h5-size $h6-size; 

// Then, use the SASS nth list function. 
@for $i from 1 through 6 {
    h#{$i} {  
        font-size: nth($sizelist, $i);
    } 
}

This will compile to:

h1 {
    font-size: 3em;
}
h2 {
    font-size: 2em;
}
etc...
adam Kiryk
  • 1,735
  • 2
  • 14
  • 14