Mixin per il dimensionamento dei caratteri Rem - Trucchi CSS

Anonim

L' remunità di dimensione del carattere è simile a em, solo che invece di ricadere è sempre relativa all'elemento radice (html) (maggiori informazioni). Questo ha un supporto browser moderno abbastanza buono, è solo IE 8 e pxversioni successive per cui dobbiamo fornire fallback.

Invece di ripeterci ovunque, possiamo usare un mixin LESS o SASS per mantenerlo pulito. Questi mixin presuppongono:

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

Utilizzo

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

(Grazie Gabe Luethje)

Un altro SCSS con un approccio diverso da 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; )

Quindi puoi fare:

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

e prendi:

body ( margin: 160px 320px 480px 640px; margin: 10rem 20rem 30rem 40rem; )