Last active
December 7, 2017 19:10
-
-
Save davidegreenwald/9b295c41223b3ec2975af1f4a448bdb1 to your computer and use it in GitHub Desktop.
2 modular typography scales for different screen sizes with CSS variables and Sass 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
/** | |
* CSS variables have 77% global browser support | |
* and don't work in IE at all | |
* so we can use Sass for a fallback | |
* @link https://caniuse.com/#search=css%20variables | |
*/ | |
/** | |
* Set fallback base font and scale ratio with Sass | |
* Use these numbers with :root when removing fallback | |
* Pick your own ratios! | |
* @link http://www.modularscale.com/ | |
*/ | |
$font-size: 1rem; | |
$ratio: 1.12; | |
$ratio-large: 1.25; | |
/* Create Sass type sizes */ | |
$h4: $font-size * $ratio; | |
$h3: $h4 * $ratio; | |
$h2: $h3 * $ratio; | |
$h1: $h2 * $ratio; | |
/* Sass second scale with larger type sizes */ | |
$h4-large: $font-size * $ratio-large; | |
$h3-large: $h4 * $ratio-large; | |
$h2-large: $h3 * $ratio-large; | |
$h1-large: $h2 * $ratio-large; | |
/** | |
* Use Sass variables with CSS variables for single variable source | |
* Replace these with above numbers in the future | |
*/ | |
:root { | |
--font-size: $font-size; | |
--ratio: $ratio; | |
--ratio-large: $ratio-large; | |
/** | |
* Set heading sizes with CSS variables | |
* any browser that can support variables will support Calc | |
* CSS Calc has 94% support | |
* @link https://caniuse.com/#feat=calc | |
*/ | |
--h4: calc(var(--font-size) * var(--ratio)); | |
--h3: calc(var(--h4) * var(--ratio)); | |
--h2: calc(var(--h3) * var(--ratio)); | |
--h1: calc(var(--h2) * var(--ratio)); | |
} | |
p { | |
font-size: $font-size; /* variable fallback for IE11 */ | |
font-size: var(--font-size); | |
} | |
h1 { | |
font-size: $h1; /* variable fallback for IE11 */ | |
font-size: var(--h1); | |
} | |
h2 { | |
font-size: $h2; /* variable fallback for IE11 */ | |
font-size: var(--h2); | |
} | |
/* switch to larger ratio at a breakpoint */ | |
@media (min-width: 600px) { | |
:root { | |
--ratio: var(--ratio-large); | |
} | |
/** | |
* 1. Variable fallback for IE11 | |
* 2. redeclare h1 size so Sass fallback will not overwrite it in the media query | |
* This method generates more code than Sass alone but preps the stylesheet | |
* for less code with vanilla CSS in the long run | |
* We will be able to change one variable (above) instead of overwriting every heading | |
*/ | |
h1 { | |
font-size: $h1-large; /* 1 */ | |
font-size: var(--h1); /* 2 */ | |
} | |
h2 { | |
font-size: $h2-large; /* 1 */ | |
font-size: var(--h2); /* 2 */ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment