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:

.mRight50{margin-right:50px}
.mLeft50{margin-left:50px}
.pRight50{padding-right:50px}
.pLeft50{padding-left:50px}
.mRight25{margin-right:25px}
.mLeft25{margin-left:25px}
.pRight25{padding-right:25px}
.pLeft25{padding-left:25px}

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.)

.mRight100{margin-right:100px}
.mLeft100{margin-left:100px}
.pRight100{padding-right:100px}
.pLeft100{padding-left:100px}
.mRight95{margin-right:95px}
.mLeft95{margin-left:95px}
.pRight95{padding-right:95px}
.pLeft95{padding-left:95px}
.mRight90{margin-right:90px}
.mLeft90{margin-left:90px}
.pRight90{padding-right:90px}
.pLeft90{padding-left:90px}
.mRight85{margin-right:85px}
.mLeft85{margin-left:85px}
.pRight85{padding-right:85px}
.pLeft85{padding-left:85px}
.mRight80{margin-right:80px}
.mLeft80{margin-left:80px}
.pRight80{padding-right:80px}
.pLeft80{padding-left:80px}
.mRight75{margin-right:75px}
.mLeft75{margin-left:75px}
.pRight75{padding-right:75px}
.pLeft75{padding-left:75px}
.mRight70{margin-right:70px}
.mLeft70{margin-left:70px}
.pRight70{padding-right:70px}
.pLeft70{padding-left:70px}
.mRight65{margin-right:65px}
.mLeft65{margin-left:65px}
.pRight65{padding-right:65px}
.pLeft65{padding-left:65px}
.mRight60{margin-right:60px}
.mLeft60{margin-left:60px}
.pRight60{padding-right:60px}
.pLeft60{padding-left:60px}
.mRight55{margin-right:55px}
.mLeft55{margin-left:55px}
.pRight55{padding-right:55px}
.pLeft55{padding-left:55px}
...

Ugh.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.