0

Is there any efficient way to write this code with less.js:

  • I've got already 3 variables colors : @vert, @violet and @orange
li {
    &:nth-child(1) {
        background: @vert;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @vert;
            }
        }
    }
    &:nth-child(2) {
        background: @violet;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @violet;
            }
        }
    }
    &:nth-child(3) {
        background: @orange;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @orange;
            }
        }
    }
}    

I thought of a mixin, but I'm not writing well: Any help please ?

.colored-menu(@number, @color) {
    &:nth-child(@number) {
        background: @color;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @color;
            }
        }
    }
}

and calling it like this:

.colored-menu(1,@vert);
.colored-menu(2,@violet);
.colored-menu(3,@orange);
TylerH
  • 20,799
  • 66
  • 75
  • 101
echayotte
  • 1
  • 3

1 Answers1

0

You can use your approach with some edits:

// mixin
.colored-menu(@number; @color) { // the docs recommends semi-colons instead of commas
  &:nth-child(@{number}) { // variable requires curly brackets for interpolation
    background: @color;
    &:hover,
    &.open {
      > .dropdown-menu li {
        background: @color;
      }
    }
  }
}

// ruleset
li {
  .colored-menu(1; @vert);
  .colored-menu(2; @violet);
  .colored-menu(3; @orange);
}

Also, consider using the each list function:

// list
@colors: @vert, @violet, @orange;

// ruleset
li {
  each(@colors, {
    &:nth-child(@{index}) {
      background: @value;
      &:hover,
      &.open {
        > .dropdown-menu li {
          background: @value;
        }
      }
    }
  });
}

The output from both approaches are the same (in this instance).

charles
  • 1,814
  • 2
  • 13
  • 19