platzhersh
platzhersh

Reputation: 1562

SCSS / SASS - Dynamic generation of CSS classes

I just came upon a situation where I wanted to automatically generate a series of css classes with help of a mixin. So I was wondering if there is a way to make this dynamically.

Basically I have classes like

.tile-1, .tile-2, .tile-3, .tile-4 ...

Where tile-2 is double the height of tile-1, tile-3 three times the height of tile-1, and so on

I also created a very simple mixin to be able to set the base-height in a scss variable and calculate it from there:

@mixin tile-height($size) {
    height: $size * $tile-height;
}

Where $tile-height is being loaded from another scss file.

Is there a way to generate my tile-x classes dynamically in the stylesheet, using the number from the classname as a mixin parameter?

Upvotes: 4

Views: 3776

Answers (1)

Bram Vanroy
Bram Vanroy

Reputation: 28427

Is this what you are looking @for?

$tile-height: 20;

@mixin tile-height($size) {
  height: $size * $tile-height + px;
}

@for $i from 1 through 5 {
  .tile-#{$i} { @include tile-height($i); }
}

Upvotes: 12

Related Questions