Skip to content

Instantly share code, notes, and snippets.

@mturnwall
Last active August 29, 2015 14:12
Show Gist options
  • Save mturnwall/57d4f72a200f7b0c401a to your computer and use it in GitHub Desktop.
Save mturnwall/57d4f72a200f7b0c401a to your computer and use it in GitHub Desktop.
Sass mixin to build font sizes using rem units and provide a fallback.
/**
* Default font size for the page.
* Leave the unit type off to make the math easier later on.
* Add this variable to the HTML element of the page.
*
* @group Fonts
*/
$font-size-base: 14;
/**
* Fallback unit type for relative fonts.
* If this variable is removed the fontSize mixin will
* not provide a fallback.
* @group Fonts
*/
$font-fallback-type: "%";
/**
* Create rem or percentage font size relative to another font size.
* This is generally a base font size for a page
*
* @param {Number} $actual - the actual font size the text should be
* @param {Number} $relative - size the rem should be relative to
* @param {String} $unitType - the unit the font should be, usually either rem or %
*
* @return {String} Generated font size
*
* @author Michael Turnwall
*/
@function getRelativeFontSize($actual, $relative, $unitType) {
@if $unitType == "rem" {
@return #{($actual/$relative)}rem;
} @else {
@return ceil(percentage($actual/$relative));
}
}
/**
* Generate a font size based on rem fonts with a fallback for older browsers
* @param {Number} $actual - the actual font size the text should be
* @param {Number} $relative ($font-size-base) - number to divide $actual by to find the rem value
*
* @requires {function} getRelativeFontSize
*
* @group Fonts
*
* @example scss
* @include fontSize(18)
* // using a $font-size-base of 14 generates
* // font-size: 129%
* // font-size: 1.28571rem
*/
@mixin fontSize($actual, $relative: $font-size-base) {
@if $font-fallback-type == "%" {
font-size: getRelativeFontSize($actual, $relative, $font-fallback-type);
} @else {
font-size: $actual;
}
font-size: getRelativeFontSize($actual, $relative, "rem");
}
@mturnwall
Copy link
Author

Usage

SASS

html {
  font-size: #{$font-size-base}px;
}
#myElement {
  @include fontSize(18);
}

Compiled

html {
  font-size: 14px;
}
#myElement {
  font-size: 129%;
  font-size: 1.2857142857rem;
}

You can also overwrite the $font-size-base variable by passing a second argument. The font will be relative to the second argument.

SASS

#myElement {
  @include fontSize(18, 20);

Compiled

#myElement {
  font-size: 90%;
  font-size: 0.9rem;
}

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