Craig O. Curtis Craig O. Curtis -4 years ago 185
Sass (Sass) Question

Dynamically Generate Class Name and CSS Attributes in Sass

I want to dynamically generate very specific class names and attributes with an iterator and conditional checker in SCSS Sass Version 3.

If divisible by half, add half at end.
If .25 suffix only, suffix with '1q'
If .75 suffix, suffix with '3q'

Example:

// margin classes
// classes m-a-0 to m-a-5, 1/4 rems specified by 1q, half, 3q
// // m-a-1q is 1/4 rem, m-a-1-1q is i.25rem

.m- {
&a-0 {
margin: 1rem * 0;
}
&a-1q {
margin: 1rem * 0.25;
}
&a-half {
margin: 1rem * 0.5;
}
&a-3q {
margin: 1rem * 0.75;
}
&a-1 {
margin: 1rem * 1;
}
&a-1-1q {
margin: 1rem;
}
&a-1half {
margin: 1rem * 1.5;
}
&a-1-3q {
margin: 1rem * 1.75;
}
&a-2 {
margin: 1rem * 2;
}
&a-2-1q {
margin: 1rem * 2.25;
}
&a-2half {
margin: 1rem * 2.5;
}
&a-2-3q {
margin: 1rem * 2.75;
}
}


Should generate:

.m-a-0{margin:0rem}.m-a-1q{margin:0.25rem}.m-a-half{margin:0.5rem}.m-a-3q{margin:0.75rem}.m-a-1{margin:1rem} ...

Answer Source

If you'll allow a slight change in naming you could do:

$count: 2;  
@for $i from 0 through $count * 4 {
  .m-a-#{ floor($i / 4) }#{ nth(null -1q -half -3q, $i % 4 + 1) } { 
    margin: $i / 4 * 1rem; 
  }
}

//  output
.m-a-0      { margin: 0rem;    }  
.m-a-0-1q   { margin: 0.25rem; }
.m-a-0-half { margin: 0.5rem;  }
.m-a-0-3q   { margin: 0.75rem; }
.m-a-1      { margin: 1rem;    }
.m-a-1-1q   { margin: 1.25rem; }
.m-a-1-half { margin: 1.5rem;  }
.m-a-1-3q   { margin: 1.75rem; }
.m-a-2      { margin: 2rem;    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download