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

CSS Arrow

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test CSS</title>
    <style>
        .arrow {
            width: 0;
            height: 0;
            border-left: solid 100px red;
            border-top: solid 50px transparent;
            border-bottom: solid 50px transparent;
        }
    </style></head><body>
    <div class="arrow">
    </div>
</body>
/html>