Last active
August 29, 2015 14:12
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
SASS
Compiled
You can also overwrite the
$font-size-base
variable by passing a second argument. The font will be relative to the second argument.SASS
Compiled