Search code examples
arrayslessless-mixins

Less mixin, extract colors from array and on hover, add darken to that array


Is it possible to darken an array with colors? Like this:

@array: @color1 @color2 @color3 @color4
.color-mix(@i) when (@i > 0) {
    .myClass {
        li:nth-child(@{i}) {
            .background-color(extract(@array, @i));
            &:hover {
              // THIS IS NOT WORKING, IS THERE A RIGHT APPROACH FOR THIS?
                .background-color(extract(darken(@array, 5.5%, @i)));
            }
        }
    .color-mix(@i - 1);
    }
}
// Iterate
.color-mix(4);

Solution

  • If I understand your question correctly, yes, you can achieve that. Below is how you do it. Your code was almost correct except that instead of trying to darken the extracted value, it was trying to extract a darkened value (which is not possible).

    @array: #fff #00f #ff0 #f00;
    
    .color-mix(@i) when (@i > 0) {
      .myClass {
        li:nth-child(@{i}) {
          .background-color(extract(@array, @i));
          &:hover {
            .background-color(darken(extract(@array, @i), 5.5%));
          }
        }
      }
        .color-mix(@i - 1); /* I have moved it because I think it was wrongly placed */
    }
    // Iterate
    .color-mix(4);
    

    One improvement that I would suggest to your code is to move the :hover selector also within the .background-color mixin like below. This makes it a bit more easier to read as there is no wrapping of a function call within another function and so on.

    @array: #fff #00f #ff0 #f00;
    
    .color-mix(@i) when (@i > 0) {
      .myClass {
        li:nth-child(@{i}) {
          .background-color(extract(@array, @i));
        }
      }
        .color-mix(@i - 1);
    }
    // Iterate
    .color-mix(4);
    
    .background-color(@color){
      &{
        background-color: @color;
        &:hover{
          background-color: darken(@color, 5.5%);
        }
      }
    }
    

    Even better would be this - just avoid the mixin if you can :)

    @array: #fff #00f #ff0 #f00;
    
    .color-mix(@i) when (@i > 0) {
      .myClass {
        li:nth-child(@{i}) {
          @color: extract(@array, @i);
          background-color: @color;
          &:hover{
            background-color: darken(@color, 5.5%);
          }
        }
      }
        .color-mix(@i - 1);
    }
    // Iterate
    .color-mix(4);