Less CSS – Generating many rules with a loop

This can be done with a recursive Mixin like this:

.makeShipSizeRules(@size) when (@size > 1) {
    &.size-@{size} {
        width: 30px * @size;
        background-image: url('Images/ship-@{size}.png');
    }
 
    .makeShipSizeRules(@size - 1);
}

We can call it in a rule with the starting size. The Mixin will continue to call itself, generating a rule for every step until the “when” condition is reached.

.board-directive {
    .ships {
        .ship {
            .makeShipSizeRules(6);
        }
    }
}

And here is the resultant CSS:

.board-directive .ships .ship.size-6 {
  width: 180px;
  background-image: url('Images/ship-6.png');
}
.board-directive .ships .ship.size-5 {
  width: 150px;
  background-image: url('Images/ship-5.png');
}
.board-directive .ships .ship.size-4 {
  width: 120px;
  background-image: url('Images/ship-4.png');
}
.board-directive .ships .ship.size-3 {
  width: 90px;
  background-image: url('Images/ship-3.png');
}
.board-directive .ships .ship.size-2 {
  width: 60px;
  background-image: url('Images/ship-2.png');
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s