dagda1 dagda1 - 3 months ago 8
Sass (Sass) Question

dynamically create classes with sass

Can I use sass and a loop to create the following:

.m-t-0 {
margin-top: 0px !important;
}

.m-t-1 {
margin-top: 1px !important;
}

.m-t-2 {
margin-top: 2px !important;
}

.m-t-3 {
margin-top: 3px !important;
}

.m-t-4 {
margin-top: 4px !important;
}

.m-t-5 {
margin-top: 5px !important;
}

.m-t-6 {
margin-top: 6px !important;
}

Answer

This is this first result you get when you search for ‘sass loop’ on Google. Here's what we have for the @for section of the referenced page:

@for $i from 1 through 4
  .#{$class-slug}-#{$i}
    width: 60px + $i

Once adapted to the example you provided, you get this:

@for $i from 0 through 6
  .m-t-#{$i}
    margin-top: 1px * $i !important