Converting px to ems with LESS

LESS is great with adding variables, mixins, operations and functions to CSS. Here is the little trick to convert pixels to ems I use when coding responsive designs:

// Create variables [optional]
@basefont: 14; // in pixels
@baseline: 20; // in pixels

// Create a converter namespace [optional]
#pxtoem {
    // Create convert mixin [required]
    .font-size( @target: @basefont, @context: @basefont ) {
        font-size: (@target / @context) + 0em;

Usage is pretty straight forward, for example if you want to make links the size of 10px then parent element font size is 16px you will use:

a {
    #pxtoem > .font-size( 10, 16 );

You can expand it with mixins for margins, paddings, etc. The most important part to remember is what you use numbers without units and then convert it to a wanted unit by adding a zero value to it.

Posted in: LESS, Mixins, Responsive, Technical, Tips, Tutorials