使用 Mixin 实现 Rem 字体大小

Avatar of Chris Coyier
Chris Coyier

rem 字体大小单位类似于 em,只是它始终相对于根 (html) 元素 (更多信息)。它在现代浏览器中拥有良好的支持,只有 IE 8 及以下版本需要提供 px 作为后备。

为了避免重复代码,我们可以使用 LESS 或 SASS 的 Mixin 来保持代码简洁。这些 Mixin 假设

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;
}

用法

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

(感谢 Gabe Luethje)


Karl Merkli 提供了另一种 SCSS 实现方法,使用了不同的思路。

@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; 
}

所以你可以这样写:

@include rem-fallback(margin, 10, 20, 30, 40);

并得到:

body {
  margin: 160px 320px 480px 640px;
  margin: 10rem 20rem 30rem 40rem; 
}