Skip Navigation
home

How to Dynamically Create Many Similar CSS Classes with Sass

Let's say you allow 5 sizes of icons in your web application and they're in 6-pixel increments: 12, 18, 24, 30, and 36. Your Sass file might have something like the following to handle this:

1.Icon {
2  &--size-12 {
3    width: 12px;
4    height: 12px;
5    font-size: 12px;
6  }
7
8  &--size-18 {
9    width: 18px;
10    height: 18px;
11    font-size: 18px;
12  }
13
14  &--size-24 {
15    width: 24px;
16    height: 24px;
17    font-size: 24px;
18  }
19
20  &--size-30 {
21    width: 30px;
22    height: 30px;
23    font-size: 30px;
24  }
25
26  &--size-36 {
27    width: 36px;
28    height: 36px;
29    font-size: 36px;
30  }
31}
32

These all look really similar, right? The class names all have the same format, and each one sets a width, height, and font-size to be the same thing. Would you believe me if I told you that it's possible to dynamically create blocks of CSS for class names in Sass?

Well, believe me! It's true!

Here's one way you can introduce a @for to do this:

1.Icon {
2  @for $i from 1 through 5 {
3    $base-size: 12;
4    $increment: 6;
5    $calculated-size: $base-size + ($i * $increment);
6
7    &--size-#{$calculated-size} {
8      width: #{$calculated-size}px;
9      height: #{$calculated-size}px;
10      font-size: #{$calculated-size}px;
11    }
12  }
13}
14

What if you don't have even increments, though? You can also loop through an array of values like this:

1$icon-sizes: 12, 16, 32, 48;
2
3.Icon {
4  @each $size in $icon-sizes {
5    &--size-#{$size} {
6      width: #{size}px;
7      height: #{size}px;
8      font-size: #{size}px;
9    }
10  }
11}
12
Back to Top