Search code examples
csslessless-mixinsunit-conversion

Convert from pixels to em


I watched a really good tutorial about bombproof webdesign from Tutsplus the other day. The instructor had an awesome function that was made in Stylus.

$base_font_size = 16

$base_font_size_ems = unit($base_font_size / 16, em)

$px = unit(1 / $base_font_size, rem)

$px_em = unit(1 / $base_font_size, em)

To call this cool function in Stylus, you would just type:

.button
  font-size: 16 * $px
  border-radius: 3 * $px solid #000

If I understand this correct. The function lets me think in pixels but outputs everything in em. Now, how do I do the same function in Less? :-)


Solution

  • The conversion for that from Stylus to Less is fairly straight-forward. The equivalent Less code would be as follows:

    @base_font_size: 16;
    @base_font_size_ems: unit(@base_font_size / 16, em);
    @px: unit(1 / @base_font_size, rem);
    @px_em: unit(1 / @base_font_size, em);
    
    .button{
      font-size: 16 * @px;
      border-radius: 3 * @px solid #000;
    }
    

    Note that the above is just a direct conversion of your code in question and would currently always result in same value for both em and rem. However em and rem would generally be same only if the root font size and the parent's font size are the same. Check here for more information about em and rem.

    The below snippet is a revised version where we have a separate mixin for doing the px to em/rem conversion. Here we set the root font size in a variable (global scope) and then we set the parent font size within each selector block (local scope) and is passed as an argument to the mixin. Based on these, the rem and em values are output as appropriate.

    @root_font_size: 32;
    
    .rem_em_px_conversion(@parent_font_size: 32){
    
      @px_rem: unit(1 / @root_font_size, rem);
      @px_em: unit(1 / @parent_font_size, em);
    }
    .div{
        .rem_em_px_conversion();
        font-size: 16 * @px_em; /* change to 16 * @px_rem for converting to rem */
        border-radius: 4 * @px_em solid #000;
        .button{
          @parent_font_size: 16; /* this is same as parent div font size */
          .rem_em_px_conversion(@parent_font_size);
          font-size: 16 * @px_em;
          border-radius: 4 * @px_em solid #000;
        }
    }