Neon Rocket

Even Neo is Impressed

RSS 2.0

Iterations in Less

Part of the beauty of Less and other CSS ‘compilers’ is to enable the author to automate tedious functions that normally must be coded by hand.

Cut Copy Paste

Cut Copy Paste (Photo credit: arthit)

Suppose you needed several classes that specified padding/margins:


No big deal, right? It wouldn’t take that long to type in; just cut and paste a bit.

Well, what if you needed them from 0-100 by 5s? (Never mind WHY you’d want to do this; this is a simple example.)



There’s a better way:

@steps: 100;

// Main Loop
.sidesX( @index ) when ( @index > 0 ) {
 (~".mRight@{index}") { .mRightX(@index); }
 (~".mLeft@{index}") { .mLeftX(@index); }
 (~".pRight@{index}") { .pRightX(@index); }
 (~".pLeft@{index}") { .pLeftX(@index); }

 .sidesX(@index - 5);

// End iteration at index zero
.sidesX( 0 ) {}<

// Individual class rendering
.mRightX( @offsetsize ) {
  margin-right: (~"@{offsetsize}px");
.mLeftX( @offsetsize ) {
 margin-left: (~"@{offsetsize}px");
.pRightX( @offsetsize ) {
 padding-right: (~"@{offsetsize}px");
.pLeftX( @offsetsize ) {
 padding-left: (~"@{offsetsize}px");

// Generate the CSS
.sidesX( @steps );
Enhanced by Zemanta