Easy Responsive Font Size CSS Trick

To look its best, text often needs to render at larger sizes on larger screens and smaller sizes on smaller screens. Unfortunately this isn't the easiest thing to achieve sanely. A straightforward approach is to set breakpoints using media queries, but this can get tedious:

responsive_fonts_media_queries.css
h1 {
  font-size: 24;
}
@media screen and (min-width: 500px) {
  h1 {
    font-size: 32;
  }
}
@media screen and (min-width: 750px) {
  h1 {
    font-size: 64;
  }
}

You'll need a set of media queries for h1, h2, h3, h4, h5, h6, and p, and the same for button text.

A more elegant solution is to set the font-size on the root html element and base other fonts off of that. You may be able to get away with only one set of media queries to change the html font-size, but you may want different types of text to scale differently, so this approach breaks down.

Even taking the design shortcut of "just use Bootstrap" doesn't get you there without some extra work. Bootstrap's responsive font sizes requires you to build your styles with Sass, which means another build step if you aren't already using Sass.

I was listening to The CSS Podcast's episode on functions and heard a great idea, though: use the CSS min() function and viewport-relative font sizes! Here's a little test:

responsive_fonts_min.css
h1 {
  font-size: min(8vw, 64px);
}
h2 {
  font-size: min(6vw, 24px);
}
p {
  font-size: min(4vw, 16px);
}

Responsive Header

Less Important Header

This text is responsive, too. Try resizing the window or rotating your phone. It will grow with the screen, but no larger than 16px.

That's a nifty trick I'll keep in mind.