Skip to content

Instantly share code, notes, and snippets.

@madastro
Forked from stowball/1-px-to-rem-mixin.scss
Created December 12, 2013 04:07
Show Gist options
  • Select an option

  • Save madastro/7923052 to your computer and use it in GitHub Desktop.

Select an option

Save madastro/7923052 to your computer and use it in GitHub Desktop.
// Mixin that allows to specify arbitrary CSS properties with and output rem with pixel fallback.
// Shorthand assignments are supported too!
// Based off http://intuio.at/en/blog/an-improved-sass-rem-mixin-for-unitless-numbers/
$baseLine: 16px;
@mixin rem($property, $values)
{
// Placeholder variables
$shorthand_px: "";
$shorthand_rem: "";
// Parameter $values might be a list of elements
@each $value in $values
{
// Current value is a valid number and greater than 0
@if $value != auto and $value != 0
{
$value: $value / ($value * 0 + 1);
$baseLine: $baseLine / ($baseLine * 0 + 1);
// Add 'px' and 'rm' to the current value and store in
// placeholder variables
$shorthand_px: #{ $shorthand_px + " " + $value + px };
$shorthand_rem: #{ $shorthand_rem + " " + ($value / $baseLine) + rem };
}
// Current value is 'auto' or 0
@else
{
// Add only 'auto' or 0 to the placeholder variables
$shorthand_px: #{ $shorthand_px + " " + $value };
$shorthand_rem: #{ $shorthand_rem + " " + $value };
}
}
// Output the CSS property in pixels and rems
#{$property}:$shorthand_px;
#{$property}:$shorthand_rem;
}
// Will need to write a command to convert standard CSS rules in to @include rem
// There's no way I'm typing that everytime!
$baseFontSize: 20px;
$baseMarginSize: 14px;
foo {
@include rem('font-size', $baseFontSize);
}
bar {
@include rem('margin-bottom', $baseMarginSize);
}
baz {
@include rem('padding', 10px 15px $baseMarginSize);
}
fish {
@include rem('line-height', 30px);
}
// Almost produces this. Not quite as neat or succinct, but, hey…
// rem = value / 16
foo {
font-size: 20px;
font-size: 1.25rem;
}
bar {
margin-bottom: 14px;
margin-bottom: .875rem;
}
baz {
padding: 10px 15px 14px;
padding: .625rem .9375rem .875rem;
}
fish {
line-height: 30px;
line-height: 1.875rem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment