Reputation: 2423
As many of you have probably noticed when building a website, larger font sizes typically require a smaller line height. I currently have a list of font sizes for headings in my SASS project, I'm looking for a function that can automatically calculate an appealing line height based on a given height. I'm currently doing the following:
$font-size--h1: 4rem;
$font-size--h2: 3rem;
$font-size--h3: 2rem;
$font-size--h4: 1.5rem;
$font-size--h5: 1.25rem;
$font-size--h6: 1.1rem;
$font-sizes: (
h1: $font-size--h1,
h2: $font-size--h2,
h3: $font-size--h3,
h4: $font-size--h4,
h5: $font-size--h5,
h6: $font-size--h6
);
@each $heading, $font-size in $font-sizes {
#{$heading} {
font-size: $font-size;
}
}
What I would like to have is a function that can take in the font size and then output an appropriate line height, so my @each
loop would look something like this:
@each $heading, $font-size in $font-sizes {
#{$heading} {
font-size: $font-size;
line-height: calculate-line-height($font-size); // Some function
}
}
Has anyone built such a function before? I found an article that describes this, but was unable to translate the function described into a working SASS function.
Upvotes: 0
Views: 894
Reputation: 2099
Here is an SCSS port of the two functions in the article you linked:
@use "sass:math";
@function getFontSize($base, $ratio, $size) {
@return $base * math.pow($ratio, $size);
}
@function getLineHeight($base, $ratio, $size, $gridSize) {
$lineHeight: math.round($base * math.pow($ratio, $size));
@return if($lineHeight % $gridSize == 0, $lineHeight, $lineHeight + $lineHeight % $gridSize);
}
(Note that I've omitted the rounding in the first function since you're using rem
instead of pt
or px
.)
To use that system, though, you'll need to restate your font size series in the same terms: a base font size, base line height, ratio between sizes, and grid size that are shared across all sizes, and then the six sizes themselves. That might look like this (though you'll need to tune the numbers):
$sizes: 1, 2, 3, 4, 5, 6;
@each $size in $sizes {
h#{$size} {
font-size: getFontSize(1rem, 1.1, 7 - $size);
line-height: getLineHeight(18px, 1.1, 7 - $size, 18px);
}
}
Here's a pen showing the entire thing.
Upvotes: 2