Responsive Font Size

Solving problems with SASS

Problems

  1. On desktop have a nice font size
  2. On desktop allow user to increase font size
  3. On mobile or small screen have a min size
  4. REM is changing sizes from desktop to mobile

Explanations

Problem 3 — On mobile or small screen have a min size — is important and often overlooked. Being overlooked is why this blog posts was written and why I noticed this issue in the first place. For example the font was 0.8rem with rem being 16px. When on mobile the rem was changed to 11px so the font became 8.8px which is too small!

Problem 4 — REM is changing sizes from desktop to mobile — is one you might have in you inherit legacy styling such that if you change the base REM to stop changing based on screen size all sorts of undesired side effects happen. For example margins and layouts become too big.

If you do not have problem 4 then one could use the solution posted at CSS-Tricks that uses css calc() originally from Mike Riethmuller.

body {
  font-size: calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum viewport width]) / ([maximum viewport width] - [minimum viewport width])));
}

Solution

// scss mixin
@mixin responsive-font-size($desktop_px, $min_px) {
  // normal situation uses rem so that a user can scale up
  font-size: $desktop_px / $root_size * 1rem;

  @media (max-width: $screen_md_min) {
    font-size: floor(($desktop_px - $min_px) * 0.8) + $min_px;
  }

  @media (max-width: $screen_sm_min) {
    font-size: floor(($desktop_px - $min_px) * 0.4) + $min_px;
  }

  @media (max-width: $screen_xs_min) {
    font-size: $min_px;
  }
}

One could add more or less steps between normal size and small screen size but the pattern is established. The trick is two fold:

  1. font-size on desktop uses rem so that a user could via browser scale up their font sizes – solves problem 1 and 2
  2. font-size on smaller screens uses pixels to prevent the changing rem size from causing the fonts to get too small (problem 4) and still keep the text and a good reading size (problem 3).

Leave a comment