Daniel Ramirez-Escudero
Daniel Ramirez-Escudero

Reputation: 4047

Automate pixel fallback using REM units throughout a project

I checked the following article in which it presented the following mixing:

rem font size with pixel fallback

@function calculateRem($size) {
  $remSize: $size / 16px;
  @return $remSize * 1rem;
}

@mixin font-size($size) {
  font-size: $size;
  font-size: calculateRem($size);
}

I feel very confortable using rem on my projects, after placing font-size: 62.5% on the html so 1rem = 10pixels.

But I would like to know if there is a mixing or a method to create a pixel fallback for any rem used in a whole project, as for example:

&:before{
    color: white;
    margin: 0 0.5rem 0 0;
    left: 0;
    text-align: center;
    top: 0;
    width: 3.2rem;
}

In this case the margin-right = 5pixels and width 32pixels. The issue with rem units is that IE8, Opera mini or Safari 3.2 is not supported. So the site would not be correctly visible from any of these browsers.

Is there a way to automate the pixel fallback using rem throughout a project?

Upvotes: 2

Views: 1859

Answers (2)

Jeffhowcodes
Jeffhowcodes

Reputation: 416

This solution will work with shortcut properties that contain mixed values.

// Global Var
$root-font-size: 16;

@mixin rem($property, $values) {
  $pxvalues: null;
  $remvalues: null;

  @each $value in $values{
    $pxvalue: null;
    $remvalue: null;
    @if type-of($value) == 'number'{
      @if ($value > 0 or $value < 0){
        $pxvalue: ($value)+px;
        $remvalue: ($value / $root-font-size)+rem;
      } @else {
        $pxvalue: $value;
        $remvalue: $value;
      }
    } @else {
      $pxvalue: $value;
      $remvalue: $value;
    }

    $pxvalues: append($pxvalues, $pxvalue);
    $remvalues: append($remvalues, $remvalue);

  }

  #{$property}: $pxvalues;
  #{$property}: $remvalues;
}

// Usage: pass pixel values without units
.foo{
  @include rem(margin, 80 auto);
}

Output:

.foo{
  margin: 80px auto;
  margin: 5rem auto;
}

Upvotes: 0

Vangel Tzo
Vangel Tzo

Reputation: 9313

Here is a solution so you can use the rem to px mixin for any property:

html {
  font-size: 62.5%;
}

@function calculateRem($size) {
  $remSize: $size / 10px;
  @return #{$remSize}rem;
}

@mixin rem($propertie, $value) {
  #{$propertie}: $value;
  #{$propertie}: calculateRem($value);
}

p {
  font-size: calculateRem(32px);
  @include rem(width, 100px);
  @include rem(margin, 50px);
}

OUTPUT

html {
  font-size: 62.5%;
}

p {
  font-size: 3.2rem;
  width: 100px; /* Fallback */
  width: 10rem;
  margin: 50px; /* FallBack */
  margin: 5rem;
}

An example: http://sassmeister.com/gist/e888e641925002b5895c

Upvotes: 1

Related Questions