"I" before "E" except Gleitzman

Posts tagged "Less"

1 post with this tag

Generating Repetitive CSS with Loops in LESS

Generating Repetitive CSS with Loops in LESS

Metaprogramming — writing code that generates other code — can be particularly useful when dealing with languages that are widely adopted yet lack advanced features. With the help of metalanguages like LESS and SCSS you can use advanced constructs (variables, looping, string formatting, etc.) to make your CSS DRYer and more fun to write.

Often in CSS you’ll find repetitive structures like the following:


// CSS for the Bamboo and Ball tiles in mahjong
.tile-0 { background-image: url(/img/tiles/bamboo_1.png); }
.tile-1 { background-image: url(/img/tiles/bamboo_2.png); }
.tile-2 { background-image: url(/img/tiles/bamboo_3.png); }
.tile-3 { background-image: url(/img/tiles/bamboo_4.png); }
.tile-4 { background-image: url(/img/tiles/bamboo_5.png); }
.tile-5 { background-image: url(/img/tiles/bamboo_6.png); }
.tile-6 { background-image: url(/img/tiles/bamboo_7.png); }
.tile-7 { background-image: url(/img/tiles/bamboo_8.png); }
.tile-8 { background-image: url(/img/tiles/bamboo_9.png); }
.tile-9 { background-image: url(/img/tiles/ball_1.png); }
.tile-10{ background-image: url(/img/tiles/ball_2.png); }
// CSS for tiles 11-16 omitted for length
.tile-17{ background-image: url(/img/tiles/ball_9.png); }

The above rules are used to create 18 mahjong tiles (9 in each suit) represented by CSS rules .tile-0 through .tile-17. Here’s an example of what the tiles look like when rendered.