DEV Community

Cover image for Sass / SCSS function to generate headings between min and max font-size
Nick
Nick

Posted on • Updated on

Sass / SCSS function to generate headings between min and max font-size

In school I thought: "Why do I have to learn about lines in terms of geometry?!" I had no good idea of why and where to use them. Some days ago I was remembering that we have learned how to use them in school but I didn't remember how to use them now so I had to look it up.

I wanted to have a function that returns the font size for a specific heading so I came up with this function f(x) = -8px * x + 68px where x is the heading from 1 to 6.

The headings in this function will start at a font size of 60px for h1 and end at a font size of 20 px for h6.

This is how I came up with this function:

f(x) = m * x + c

maxFontSize = 60px
minFontSize = 20px
m = (minFontSize - maxFontSize) / (6 - 1)
c = maxFontSize - m

f(x) = -8px * x + 68px
Enter fullscreen mode Exit fullscreen mode

Finally in SCSS:

@function getHeadingFontSize($minFontSize, $maxFontSize, $heading) {
  $m: ($minFontSize - $maxFontSize) / (6 - 1);
  $c: $maxFontSize - $m;
  @return $m * $heading + $c;
}

// Font size of headings
@for $i from 1 through 6 {
  h#{$i} {
    font-size: getHeadingFontSize(20px, 60px, $i);
  }
}
Enter fullscreen mode Exit fullscreen mode

And this generates the following CSS:

h1 {
  font-size: 60px
}

h2 {
  font-size: 52px
}

h3 {
  font-size: 44px
}

h4 {
  font-size: 36px
}

h5 {
  font-size: 28px
}

h6 {
  font-size: 20px
}
Enter fullscreen mode Exit fullscreen mode

I don't know if this is in some way useful because the designers in your team would just give you the sizes but ... yay.

Top comments (0)