What is the equivalent of Scss' emCalc()
in less?
padding: emCalc(24px);
in Scss will calculate em based on the viewpoint and zoom level. Is there any built-in function in less?
What is the equivalent of Scss' emCalc()
in less?
padding: emCalc(24px);
in Scss will calculate em based on the viewpoint and zoom level. Is there any built-in function in less?
With LESS you can build your own functions. I use this function with the grunt-contrib-less package. The formatting is slightly different from the usual less functions formatting. Note you need to insert less as a parameter with this package.
Now you can just call this function in your LESS stylesheets as
Which will compile to
Note ems will still be relative to the container's css. So the font-size of 1em will not be 16px if the wrapping div has a font-size set of 0.8em for example.
Update: The non-grunt-contrib-less version
If you put this in a javascript file which you include in your html before your less file, you can use the function as stated above.
You could do this to convert px to em.
LESS doesn't have such a feature, according to documentation.
Built-in unit or convert functions do not provide such a convertion.
Note that Scss' implementation of this function assumes convertion using one global font-size value. You can easily achieve same thing in LESS with the use of variables:
And then use it like this:
Code above compiles to:
Note that this (and Scss' version, too) is not the way that real em work, because in CSS dimensions specified in
em
are computed based on font size of element on which they are used.If you're compiling your LESS on the server side, and I personally would never do otherwise you can do this with LESS mixins and no custom functions.
That of course means you can't automatically calculate based on the size of the current node, but thwat's a little sounding scary to me. Here's another way to just convert pixels to ems.
Global less mixins
Example usage
Note that I use the same
.convertEm(..)
mixin for both pixels and ems, since you may not even know if the value is passed as a parameter. The guarded mixin correctly picks the right formula to convert.This generates this css
This all assumes 1em corresponds to 16px. If not you can change the default or pass it in depending upon the context you're in:
Disclaimer: I still don't fully understand how or if server generated LESS works can work with custom javascript functions so I'm assuming that when you generate server side you can't add custom functions. If I'm wrong please someone let me know!
If you're compiling your LESS on the server side, you can do this with CSSHub
This generates this css