Skip to content

Instantly share code, notes, and snippets.

@Jonic
Created January 24, 2012 16:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jonic/1670945 to your computer and use it in GitHub Desktop.
Save Jonic/1670945 to your computer and use it in GitHub Desktop.
/*
Following this suggestion by @aral:
https://twitter.com/#!/aral/status/161833507423916032 and
https://twitter.com/#!/aral/status/161833979736096769
I realised that a CSS Pre-processor could help save some time here if you
use the same values for px and rem.
This works in SCSS:
*/
@mixin font_size($size) {
font-size: #{$size}px;
font-size: #{$size}rem;
}
/* Usage
*/
html {
font-size: 1px;
}
body {
@include font_size(16); // 16px/rem
}
h1 {
@include font_size(24); // 24px/rem
}
@aral
Copy link

aral commented Jan 24, 2012

Also:

@mixin rem($attribute, $value) {
    #{$attribute}: #{$value}px;
    #{$attribute}: #{$value}rem;
}

@aral
Copy link

aral commented Jan 24, 2012

So you can do things like:

.myClass {
  @include rem(margin-bottom, 12); 
}

@Jonic
Copy link
Author

Jonic commented Jan 24, 2012

Brilliant - I was just this second figuring out line-height and margin - didn't think of this!

@laurakalbag
Copy link

So this works really well, but Aral uncovered some problems you get by setting html { font-size: 1px }

Which means we now need a version that does something like font-size: #{$size}rem/16; so it can be used with html { font-size: 16px } Except that just results in 10px/16 in the CSS, not the result of the calculation.

Any ideas?

@danshearmur
Copy link

@mixin font_size($size) {
font-size: #{$size}px;
font-size: #{$size/16}rem;
}

@laurakalbag
Copy link

laurakalbag commented Jul 17, 2012 via email

@danshearmur
Copy link

No worries.

The #{xyz} is a string substitution, so your original attempt just appended some characters to the end of rule. But inside the #{...} you can do basic operations on the variable $size. The number will change before being inserted into the string that ends in 'rem'.

@chriseppstein
Copy link

This will clean up if you pass in a number with px units instead of glomming it on with interpolation. Interpolation causes the number to be cast to a string which is why the division doesn't do anything. Also, it's more obvious to a reader what font_size(16px) is doing.

@aral
Copy link

aral commented Jul 18, 2012

I know that this Gist is for SASS, but here's a link to a Gist I just created for Stylus that solves the same problem (I’m currently working with Stylus on the Breaking Things site.) It’s a work in process but you can see where I’m going with it.

https://gist.github.com/3138403

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment