LESS CSS Font-Size (Parametric Mixin) Function for Pixel to REM

I made a Parametric Mixin in LESS that will convert your pixel sizes to REM.

/*define this mixin first - make sure @target_size is greater than 0*/
.calc_font_size (@target_size:16px, @base_size:16px) {
@rem:(( round((@target_size / @base_size) * 10000) ) / 10000);/*so it can be rounded a bit more*/
font-size:~`"@{rem}".match(/\d+\.?\d+/) + 'rem'`;
/*set the body font size*/
body {font-size:100%;}
/*example to use*/
#footer {.calc_font_size(12px);}/*pass in the font-size you want in pixels*/

That will generate the following CSS

body {font-size:100%;}
#footer {font-size:12px; font-size:0.75rem;}

This mixin will output the size in pixels first then output them in REM.


Comments -49-0 of 4 to “LESS CSS Font-Size (Parametric Mixin) Function for Pixel to REM”

  1. -49 · Carlos Camacho says:

    tried your code, but less compiler keeps giving me an error on the line:

    font-size:~`”@{rem}”.match(/\d+\.?\d?/) + ‘rem’`;

    This is the error:

    Compiler Errors
    JavaScript evaluation error: `”1px”.match(/\d+\.?\d?/) + ‘rem’` (Line: 67)
    Filename: C:\Web_Sites\Miscelaneos\HTML5\Twitter Bootstrap\Less Version\less\type.less

    I’m using Crunch to compile my less files…

    Tried changing all the quotations, to no avail…

    Any thoughts?

  2. -48 · blogger says:

    I’m using the LESS.app for Mac at work and have also used WinLess for my home PC and haven’t had a problem.

    Although I realize now that the regex was slightly wrong and was causing things to be rounded more than it should of. Also if you pass 0px, it will return “nullrem”. However, even with those problems, it should still compile.

    I’ve updated the post with a better regex for the mixin. But I’m not sure why Crunch! won’t compile it. I had it installed at one time, but didn’t like how laggy it ran.

  3. -47 · Zander says:

    I use this:

    // .font-size(16);
    .font-size(@sizeValue: @baseFontSize){
    @remValue: (@sizeValue / @baseFontSize);
    font-size: ~”@{sizeValue}px”;
    font-size: ~”@{remValue}rem”;

  4. -46 · Anonymous says:

    Crunch shows an error because it does not compile javascript functions, in this case .match()

Leave a Comment

Comments are reviewed before publishing to prevent spam.