Created
December 11, 2015 17:15
-
-
Save JoeCianflone/2dc5bccfb98ae6a01a2b to your computer and use it in GitHub Desktop.
PX to Unitless line-height conversion and font fallbacks
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
// I hate converting units so here's how to do | |
// px to rem conversion with a fallback to px | |
// for older browsers... | |
/** | |
* Resize font from one type to another | |
* @param {[type]} $fontSize the font size that you want | |
* @param {[type]} $toUnit: rem the unit you want to convert to | |
* @param {[type]} $fromUnitSpecific: px default unit we're going to convert from (if you don't set it) | |
* | |
* Example 1: | |
* @include font-size(22px); | |
* Result | |
* font-size: 22px; // generates a fallback for rems | |
* font-size: 2.2rem | |
* | |
* Example 2: | |
* @include font-size(22em, "px"); | |
* Result: | |
* font-size: 22px; | |
* | |
*/ | |
@mixin font-size($fontSize, $toUnit: rem, $fromUnitSpecific: px) { | |
$currentUnit: unit($fontSize); | |
$currentValue: get-value($fontSize); | |
@if $currentUnit == "" { | |
$currentUnit: $fromUnitSpecific; | |
} | |
@if $currentUnit == "px" { | |
@if $toUnit == "rem" { | |
font-size: unquote(($currentValue) + px); | |
font-size: unquote(($currentValue / 10) + $toUnit); | |
} | |
@else if $toUnit == "em" { | |
font-size: unquote(($currentValue / 10) + $toUnit); | |
} | |
} | |
@else if $currentUnit == "rem" or $currentUnit == "em" { | |
@if $toUnit == "px" { | |
font-size: unquote(($currentValue * 10) + px); | |
} | |
@else { | |
font-size: unquote(($currentValue) + $toUnit); | |
} | |
} | |
} |
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
// helper function to make sure the unit type (px, rem) | |
// is removed we want just the raw value no unit | |
@function get-value($n) { | |
@return $n / ($n * 0 + 1); | |
} | |
// pretty simple eh? | |
@function get-line-height($font-size, $line-height) { | |
@return get-value($line-height / $font-size); | |
} | |
// Usage: | |
// Let's say you have an element that is going to be | |
// 26px font-size and you want a line-height of 32px | |
// you don't want to set 32px as the height because | |
// that value will cascade down to child elements | |
// but if you're like me you're too lazy to do | |
// math all the time... | |
.foo { | |
font-size: 26px; | |
line-height: get-line-height(26px, 32px); //1.23077 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment