Convert px to em in Less

后端 未结 7 1578
独厮守ぢ
独厮守ぢ 2021-01-01 07:34

What is the equivalent of Scss\' emCalc() in less?

padding: emCalc(24px);

in Scss will calculate em based on the viewpoint and

7条回答
  •  北海茫月
    2021-01-01 07:41

    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.

    em: function(less, fontsize, basefontsize){
        if (less.functions.functionRegistry.get('ispixel')){
            basefontsize = (basefontsize) ? basefontsize.value : 16
            return fontsize.value/basefontsize+'em';
        }
    }
    

    Now you can just call this function in your LESS stylesheets as

    .class{
        font-size:em(16px);
    }
    

    Which will compile to

    .class{
        font-size:1em;
    }
    

    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.

    $.extend(less.functions, {
        em: function(fontsize, basefontsize){
            if (this.ispixel(fontsize)){
                basefontsize = (basefontsize) ? basefontsize.value : 16
                return new(tree.Dimension)(fontsize.value/basefontsize,'em');
            }
        }
    }
    

提交回复
热议问题