loading...
Cover image for How to Dynamically Create Many Similar CSS Classes with Sass

How to Dynamically Create Many Similar CSS Classes with Sass

ashleemboyer profile image Ashlee Boyer Updated on ・2 min read

Originally posted on my blog.

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:

.Icon {
  &--size-12 {
    width: 12px;
    height: 12px;
    font-size: 12px;
  }

  &--size-18 {
    width: 18px;
    height: 18px;
    font-size: 18px;
  }

  &--size-24 {
    width: 24px;
    height: 24px;
    font-size: 24px;
  }

  &--size-30 {
    width: 30px;
    height: 30px;
    font-size: 30px;
  }

  &--size-36 {
    width: 36px;
    height: 36px;
    font-size: 36px;
  }
}

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:

.Icon {
  @for $i from 1 through 5 {
    $base-size: 12;
    $increment: 6;
    $calculated-size: $base-size + ($i * $increment);

    &--size-#{$calculated-size} {
      width: #{$calculated-size}px;
      height: #{$calculated-size}px;
      font-size: #{$calculated-size}px;
    }
  }
}

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

$icon-sizes: 12, 16, 32, 48;

.Icon {
  @each $size in $icon-sizes {
    &--size-#{$size} {
      width: #{size}px;
      height: #{size}px;
      font-size: #{size}px;
    }
  }
}

Did you know I have a newsletter? πŸ“¬

If you want to get notified when I publish new blog posts or make major project announcements, head over to https://ashleemboyer.com/newsletter.

Posted on Dec 20 '19 by:

ashleemboyer profile

Ashlee Boyer

@ashleemboyer

Dog mom to Trooper & Tango | Engineer of software | Lover of learning | Partner of Zach | She/her | HOH | #SpooniesWhoCode

Discussion

markdown guide
 

love this trick!

maps combined with @each loops can also DRY up your code:

$gutter-column-sizes: (
    none: 0,
    sm: $unit / 6,
    md: $unit / 4,
    lg: $unit / 2,
    xl: $unit,
);

@each $gutter-column-size-key, $gutter-column-size-value in $gutter-column-sizes {
    .gutter-column--#{$gutter-column-size-key} {
        padding-inline-start: $gutter-column-size-value;
        padding-inline-end: $gutter-column-size-value;
    }
}
 
 

I haven't used SASS in a long time but it has for loops now?! damn

 

SCSS is really a bag of tricks I need to learn more about

 
 

Hello, Ashlee!

I used to create column systems with the SASS @for loop... Never thought using it for things like this! Thank you so much! SASS indeed can be really powerful :)