Skip to content

Instantly share code, notes, and snippets.

@RustBeard
Last active December 31, 2018 19:24
Show Gist options
  • Save RustBeard/a1836d4c9e15b7ee53498ff79b6e7aef to your computer and use it in GitHub Desktop.
Save RustBeard/a1836d4c9e15b7ee53498ff79b6e7aef to your computer and use it in GitHub Desktop.
Ideal margins

Ideal margins

Sass function that calculates margin from letter.

Syntax

textMargin($top_or_bot, $margin, $fontSize, $lineHeight)
eg.: margin-bottom: textMargin('bot', 20, 2.25, 1.5);

This returns margin in "em" unit.

Values and variables

Font

  • $global-font-size - font size, defined for whole document (corresponding to 1 em; in px)
  • $font-cap-height - capital letter proportions, when line height is 1 (proportions, without units; see image.png)
  • $font-baseline - space between bottom border of line height and letter baseline, when line height is 1 (proportions, without units; see image.png)

Function

  • $top_or_bot - the margin is top or bottom?
  • $margin - margin value (in px)
  • $fontSize - font size (in em)
  • $lineHeight - line height (proportions, eg. 1.333)

To do

  • passed values should be given in any unit
$global-font-size: 14px; // sample value
$font-cap-height: 0.717; // value for Lato font
$font-baseline: 0.113; // value for Lato font
@function textMargin($top_or_bot, $margin, $fontSize, $lineHeight) {
$font_size: $fontSize * $global-font-size;
$line_height: $lineHeight * $font_size;
$cap_height: $font_size * $font-cap-height;
$lineheight_surplus: ($line_height - $cap_height) / 2;
$top_space: 1 - $font-cap-height - $font-baseline;
$diff: (($top_space - $font-baseline) * $font_size) / 2;
$top_surplus: $lineheight_surplus + $diff;
$bot_surplus: $lineheight_surplus - $diff;
$margin_value: $margin - $bot_surplus;
@if $top_or_bot == 'top' {
$margin_value: $margin - $top_surplus;
}
$margin_value: ($margin_value / $font_size) * 1em;
@return($margin_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment