Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created June 5, 2014 21:33
Show Gist options
  • Save bennadel/723fb228d2518d7dd790 to your computer and use it in GitHub Desktop.
Save bennadel/723fb228d2518d7dd790 to your computer and use it in GitHub Desktop.
Passing Rulesets To Mixins In Less CSS
span.alpha {
background-position: 0px 0px;
content: "alpha is the awesome";
border-top: 0px ;
}
span.beta {
background-position: 50px 0px;
content: "beta is the awesome";
}
span.theta {
background-position: 100px 0px;
content: "theta is the awesome";
}
span.omega {
background-position: 150px 0px;
content: "omega is the awesome";
border-bottom: 0px ;
}
// I loop over the given list and apply the given ruleset on each iteration. During
// the iteration, the loop context provides several variables:
// --
// @it - the current item of iteration.
// @index - the current iteration index.
// @length - the length of the list being iterated.
// @first - is true on the first iteration of the loop.
// @last - is true on the last iteration of the loop.
// @mid - is true when the iteration is neither first nor last.
// --
.list-loop( @list ; @ruleset ) {
@length: length( @list ) ;
// Initiate the loop.
.looper( 1 ) ;
// I am the recursive portion of the loop.
.looper( @index ) when ( @index <= @length ) {
// Set the current value of the iteration.
@it: extract( @list, @index ) ;
// Set values that the rules can used for context.
// --
// NOTE: This is using JavaScript since LESS doesn't seem to allow me to set
// the result of an equality check.
@first: `( @{index} == 1 )` ;
@last: `( @{index} == @{length} )` ;
@mid: `! ( @{first} || @{last} )` ;
// Invoke the given ruleset.
// --
// CAUTION: All variables defined in this set of mixins will be made
// available to the scope of the ruleset when it is evaluated.
@ruleset();
// Call recursively for next iteration.
.looper( @index + 1 ) ;
}
}
// ---------------------------------------------------------- //
// ---------------------------------------------------------- //
// When looping over the list, @{it} contains the current item in the iteration.
// The ruleset will then be "invoked" for each value of @{it}.
.list-loop(
alpha, beta, theta, omega ;
{
span.@{it} {
background-position: ( ( @index - 1 ) * 50px ) 0px ;
content: "@{it} is the awesome" ;
& when ( @first ) {
border-top: 0px ;
}
& when ( @last ) {
border-bottom: 0px ;
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment