FONT SIZING WITH REM / EM / PX

by in , 0

The rem font-size unit is similar to em, only instead of cascading it's always relative to the root (html) element (more information). This has pretty good modern browser support, it's just IE 8 and down we need to provide px fallbacks for.
Instead of repeating ourselves everywhere, we can use a LESS or SASS mixins to keep it clean. These mixins assumes:

This code also use "vairable" in CSS

html {
  font-size: 62.5%; /* Sets up the Base 10 stuff */
}
.font-size(@sizeValue) {
  @remValue: @sizeValue;
  @pxValue: (@sizeValue * 10);
  font-size: ~"@{pxValue}px"; 
  font-size: ~"@{remValue}rem";
}
@mixin font-size($sizeValue: 1.6) {
  font-size: ($sizeValue * 10) + px;
  font-size: $sizeValue + rem;
}

Usage

p {
  .font-size(13);
}
p {
  @include font-size(13);
}

Another SCSS one with a different approach by Karl Merkli:
@function strip-unit($num) {
  @return $num / ($num * 0 + 1);
}

@mixin rem-fallback($property, $values...) {
  $max: length($values);
  $pxValues: '';
  $remValues: '';

  @for $i from 1 through $max {
    $value: strip-unit(nth($values, $i));
    $pxValues: #{$pxValues + $value*16}px;

    @if $i < $max {
      $pxValues: #{$pxValues + " "};
    }
  } 

  @for $i from 1 through $max {
    $value: strip-unit(nth($values, $i));
    $remValues: #{$remValues + $value}rem;

    @if $i < $max {
      $remValues: #{$remValues + " "};
    }
  } 
  
  #{$property}: $pxValues; 
  #{$property}: $remValues; 
}
So you can do:
@include rem-fallback(margin, 10, 20, 30, 40);
and get:
body {
  margin: 160px 320px 480px 640px;
  margin: 10rem 20rem 30rem 40rem; 
}

Leave a Reply