Reading list Switch to dark mode

    Create dynamic variables using loop in Less

    Updated 28 March 2024

    Create dynamic variables using loop in Less

    I hope you have gone through my previous blogs related to Less. So based on that I came up with a new blog today, in which I will explain that how you can create dynamic variables in your Less file. So here is a less code to generate dynamic variables.

    @suffix: 'px';
    
    .mixin-loop(10,'temp'); // this will iterate from 10 to 1
    
    .mixin-loop (@i,@j) when (@i > 0) { //on first call, @i = 10 and @j = 'temp'
    
        @tmp:~"@@{j}_@{i}@{suffix}"; // it will give @temp_10px
        @{tmp}: @i/16rem;            // now in variable @temp_10px: 0.625rem
    
        .mixin-loop(@i - 1,@j); //calling mixin again with decrement of 1 in @i
    }

    In above example, I called a mixin with two arguments, you can add more depending on your need. So when mixin is called there is a condition in it which checks the value of @i is greater than 0 or not. If the value is greater than 0 then it flows inside and create dynamic variable and then again calls itself till when the condition become false.

    In the body of mixin, I have written a line of code which is generating dynamic variable, i.e, @tmp:~”@@{j}_@{i}@{suffix}”;

    Lets understand this code for its first iteration when @i=10 and @j=’temp’ and @suffix=’px’. Put the respective values of variables, i.e.

    Searching for an experienced
    Magento Company ?
    Find out More

    @tmp:~”@temp_10px”;       //@tmp:~”@@{j}_@{i}@{suffix}”;

    now @tmp variable contains the string “@temp_10px”

    Lets consider second line, i.e. @{tmp}: @i/16rem;

    in this code, replace the value of @tmp variable with its value, i.e. @temp_10px : 10/16rem;

    finally, @temp_10px: 0.625rem;

    and then I  again called mixin with decrement of 1 in first argument so that loop continues till the condition become false. Finally following CSS will be generated from the above LESS code.

    @temp_10px: 0.625rem;
    @temp_9px: 0.5625rem;
    @temp_8px: 0.5rem;
    @temp_7px: 0.4375rem;
    @temp_6px: 0.375rem;
    @temp_5px: 0.3125rem;
    @temp_4px: 0.25rem;
    @temp_3px: 0.1875rem;
    @temp_2px: 0.125rem;
    @temp_1px: 0.0625rem;

    You can change/modify variables name depending on your need, this is only for those who do not want no calculate the font pixels in rem unit manually. So the formula is written in it and then it generates the equivalent unit in rem from px.

    So that’s it in today’s article.  Try this and if you have any query then just comment below 🙂

    . . .

    Leave a Comment

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


    2 comments

  • Rob
    • ashutosh srivastava (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home