2

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

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou for such a fantastic and detailed response. I think I'll use the unit function... but it's starting to feel a little like I sass is winning.
Just in incase anyone else looks at this. The unit function was less 1.3.2 . Thought that might be useful as I just spent 2 hours wondering why it wouldn't compile when my compiler was out of date!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.