Skip to content

Instantly share code, notes, and snippets.

@IainIsCreative
Last active February 8, 2023 17:07
Show Gist options
  • Save IainIsCreative/d3df585d2ebd78a06b6a to your computer and use it in GitHub Desktop.
Save IainIsCreative/d3df585d2ebd78a06b6a to your computer and use it in GitHub Desktop.
A simple mixin for easy writing of font sizes and line heights, in rems. Also includes an option for writing type in ems.
/**
*
* SCSS Type Setting Mixin
*
* For easier writing of font sizes and line-heights, relatively.
* This can be used for writing base styles, but also specific ones if necessary.
*
**/
// Root Font Size Variable — best to avoid changing unless you like risks.
// If you're relying on it **relatively** with ems, be careful.
$root-font-size: 16!default;
/**
*
* Type Setting Mixin
*
* Let all your relative type size worries wash away with this mixin.
* This mixin requires a target value, and a line height that will output a
* font-size in rems as a default. In addition, if a context value is given,
* the font size will be written in ems instead.
*
* Example (using rems):
*
* h1 {
* @include type-setting(32, 36);
* }
*
* Output:
*
* h1 {
* font-size: 2rem;
* line-height: 1.125;
* }
*
*
**/
@mixin type-setting($target, $line-height, $context: null) {
// Is the target value unitless?
@if unitless($target) {
// Is it relying on a context value?
@if $context != null {
// Is the context unitless? If so, write out the target value in ems.
@if unitless($context) {
font-size: ($target / $context) * 1em;
} @else {
@error 'Your value for `$context` is not unitless.';
}
}
// Write out the target value in rems.
@else {
font-size: ($target / $root-font-size) * 1rem;
}
} @else {
@error 'Your value for `$target` is not unitless.';
}
// Line Height should be unitless.
@if unitless($line-height) {
// Line height should almost always be unitless, just simple math.
line-height: ($line-height / $target);
} @else {
@error 'Your value for `$line-height` is not unitless.';
}
}
/**
*
* Apply Typographic Settings
*
**/
@if $root-font-size != 16 {
// So you decided to change that value? Okay pal, you asked for it...
html {
font-size: $root-font-size * 1px;
}
}
body {
@include type-setting(18, 22);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment