wcpro wcpro - 3 months ago 17
Less Question

Dynamic column based on class names in LESS

I'm trying to do something like this

.col-@{index} {
width: @col-n-width;
left: {index - 1 } * @col-n-width;
}


But not sure how to access the {index} variable inside. Is that even possible?

Answer

The @{} syntax is used only when you need to interpolate variables in property names or selectors or URLs etc. It is not required when all you need to do is plain math operations. Just reference it as @index like in the below sample.

.col-@{index} {
  width: @col-n-width;
  left: (@index - 1) * @col-n-width;
}

For example if you are trying to write a loop/mixin, the code would be something like the below:

@col-n-width: 200px;

.create-cols(@index) when (@index > 0) {
  .col-@{index} {
    width: @col-n-width;
    left: (@index - 1) * @col-n-width;
  }
  .create-cols(@index - 1);
}
.create-cols(5);

Note: The @index must be a variable defined in your Less file. Less compiler cannot read the HTML and dynamically create classes based on it. In the worst case, you'd at least have to use client-side compilation through JS using less.modifyVars() but client-side compilation of code is generally not recommended.