user1010892
user1010892

Reputation: 1189

.less output variable not declaration

I know that you can do this in SASS

@pxtoem(@target, @context) {
 (@target/@context)+0em }

.something{
  font-size: @pxtoem(24, 16);
}

Is this possible in .less? Sorry my understanding here is quite limited but it seems to me that .less is expecting the calculation to output a css declaration?

Just to be clear, I don't want to have a mixin for each time I need to use this (bg position, font-size, line height etc)

Thanks

Upvotes: 2

Views: 788

Answers (1)

ScottS
ScottS

Reputation: 72261

Yes, from mixins, LESS outputs CSS declarations or a variable but not a value.

Best for your situation

The easiest way to get what you want is to avoid a mixin and just use ordinary operations and the unit() function:

.something {
    font-size: unit(24 / 16, em);
}

Outputs:

.something {
  font-size: 1.5em;
}

Outputting a Variable

A variable can be output, but it will still function with the normal scoping and "constant" type behavior of a LESS variable. So consider the following code. It shows that used once, it works fine (#1), but twice gives only the final value calculated for both items (#2), so to avoid that, if you needed to call it more than once per class block, you would need to get into some serious nesting of mixins within that class (#3).

.divideToEm(@target, @context) {
   @divideToEm: (@target / @context) + 0em;
}

.something { /* #1 */
   .divideToEm(24, 16);
   font-size: @divideToEm;
}

.somethingElse { /* #2 */
   .divideToEm(24, 16);
   font-size: @divideToEm;
   .divideToEm(12, 24);
   margin-right: @divideToEm;
}

.somethingElse2 { /* #3 */
   .setSize() {
   .divideToEm(24, 16);
    font-size: @divideToEm;
   }
   .setMargin() {
   .divideToEm(12, 24);
   margin-right: @divideToEm;
  }
  .setSize();
  .setMargin();
}

Outputs:

.something {
  font-size: 1.5em;
}
.somethingElse {
  font-size: 0.5em; /* <-- probably NOT expected */
  margin-right: 0.5em;
}
.somethingElse2 {
  font-size: 1.5em;
  margin-right: 0.5em;
}

Upvotes: 2

Related Questions