No Time Dad

A blog about web development written by a busy dad

Responsive Font Size Example

I stumbled across this responsive font-size technique while looking at another css framework. I borrowed their approach and modified it slightly to fit my needs. The idea behind it is that a default font-size value is set using a css custom property and the value is increased as the page width increases via media queries.

/* styles.css */
:root {
  --font-size: 16px;

body {
  font-size: var(--font-size);

@media (min-width: 768px) {
  :root {
    --font-size: 18px;
@media (min-width: 1024px) {
  :root {
    --font-size: 20px;
@media (min-width: 1440px) {
  :root {
    --font-size: 22px;
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Font Size</title>
  <link rel="stylesheet" href="styles.css">
    Responsive font size! Resize page to see the font-size change

I usually define css custom properties in the :root selector, but this is personal preference. There isn’t anything wrong with defining them in the html selector or in any other selector, as long as I don’t try to access it where it isn’t available. For example, if I defined it one of two sibling selectors, it wouldn’t be available to both. The :root selector is more global, so I don’t have to worry about scope issues when I try to access the custom property.

The name I chose for the this css custom property is --font-size, but it could be anything. I thought that name made the most sense. Once the custom property is defined, I set the font-size property in the body selector to have the value of the --font-size custom property.

The last thing to do is write the media queries. These are “mobile first” (min-width) breakpoints. The widths can be any value, but I used a few from Chrome’s dev tools. Each media query updates the value of the css custom property --font-size, which increases the font size of all text in the body element.

Why increase the font size on a page as the width increases? Small text on large screens is sometimes hard to read. Increasing the size accordingly will help users read the content. This example was a broad, using the body element. Most likely the responsive text would be used inside specific elements.