Carl Thomas Carl Thomas - 4 months ago 16
CSS Question

Calculate just a value in less

In less I can create a function which will convert px into em and return just the value

@em($target, $context: 16px) {
@return ($target / $context) * 1rem;
}


This way I can use the function like

.body {
font-size: em(22px);
padding: 0 em(10px);
}


which will output

.body {
font-size: 1.375em;
padding: 0 0.625em;
}


However in less, the only way I can see to do the same function, is to pass the selector into the function too

.em(@selector, @target, @context: 16px) {
@{selector}: unit((@target / @context), em);
}


And it needs to be used in the following way

.body {
.em(font-size: 22px);
}


Which will output

.body {
font-size: 1.375em;
}


This way is fine if I have one selector and one value, but as in the Sass example above, if I need a padding with a
0
and a
0.675em
, then I cannot use the Less function to do this.

Is there a way to return just a value from a function in Less just like Sass does, so I do not have to pass the selector into the function?

Answer

In short, no, you can't define "true" functions in Less. So for the particular use-case the most compact approach is something like this:

@context: 16px;
@u: 1em / @context;

.body {
    font-size: 22 * @u;
    padding: 0 10 * @u;
}

Or this:

@context: 16px;
@u: 1em / @context;

.body {
    font-size: @u * 22px;
    padding: 0 @u * 10px;
}

whichever you find more readable (note that arithmetic expressions require parens if you use --strict-math=on option).

Comments