Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LESS call a mixin dynamically

Tags:

css

mixins

less

How do you call a mixin dynamically?

A use case might be to generate a style guide:

// The mixin which should be called
.typography-xs(){
  font-family: Arial;
  font-size: 16px;
  line-height: 22px;
}

// The mixin which tries to call typography-xs
.typography-demo(@typographyName, @mixinName) {
  @{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    @mixinName();
  }
}

// Example call of .typograhpy-demo
.typography-demo(xs, typography-xs);

Is such a dynamic call possible at all with less css?

like image 327
jantimon Avatar asked Jan 29 '26 11:01

jantimon


1 Answers

You cannot at present dynamically call as you desire. You can, however, set it up slightly differently using pattern matching, like so:

// The mixin which should be called
.typography(xs){
  font-family: Arial;
  font-size: 16px;
  line-height: 22px;
}

// The mixin which tries to call typography-xs
.typography-demo(@typographyName) {
  @{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

// Example call of .typograhpy-demo
.typography-demo(xs);

Using pattern matching, you can then create other patterns, such as:

.typography(xl){
  font-family: Arial;
  font-size: 32px;
  line-height: 44px;
}

.typography(times){
  font-family: 'Times New Roman';
  font-size: 16px;
  line-height: 22px;
}

Now you can call pattern xl or times and have it generate the code. Essentially, take whatever you were going to use after the hyphen (like your -xs) to distinguish your various typography groups, and remove the hyphen and use that name as your pattern to match the mixins to.

Additionally, I would add a means of putting a selector before the @{typographyName} like so:

.typography-demo(@typographyName, @selector: ~".") {
  @{selector}@{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

This way it generates a class by default, but could be made into an id or any selector string up to the @{typographyName}.

like image 115
ScottS Avatar answered Jan 31 '26 02:01

ScottS