John Cheesman

Responsive Font Sizes

Code

How to scale text and other dimensions using media queries.

I’ve always liked the idea of scaling the base font size using media queries, ever since I first encountered the technique in Josh Hopkins’ Fluid Baseline Grid.

In recent projects I’ve experimented with three levels of scaling: for small, medium and large screens, with base font sizes of 14px, 16px and 18px respectively. To achieve this I set the font-size for html in percent as follows:

    html {
        font-size: 87.5%; // Small

        @include bp(medium) {
            font-size: 100%; // Medium
        }

        @include bp(large) {
            font-size: 112.5%; // Large
        }
    }

This will suffice to scale text that inherits its size from the html element. To scale the layout as a whole we will need to make consistent use of a relative unit.

Using rems with a pixel fallback is probably the most straightforward option and can be implemented dryly using a mixin like rem. The pixel value passed to the mixin will be converted to rems and will end up being computed back to the same values on medium size screens. For small and large screens the base value will be scaled up or down by the percentages we set on the html element.

    h1 {
        @include rem(font-size, 36px);
        @include rem(margin, 0 0 24px 0);
    }