Dynamic Type on the Web

This site now supports Dynamic Type on iOS and iPadOS. If you go to System Settings on your iPhone or iPad, and change the setting for Display & Brightness > Text Size, you’ll see the change reflected on this website.

This is a big win for accessibility: many folks make this adjustment on their device to match their abilities. Just because you can read a tiny font doesn’t mean that I can. It also is a win for consistency: my site’s font size matches the other text that a visitor sees on their device.

The best part is that this improvement can be realized with only a few lines of CSS:

html {
font-size: 0.9em;
font: -apple-system-body;
font-family: "Avenir Next", "Helvetica Neue", sans-serif;
}

What’s going on here?

The font-size property sets the default text size for the page. All browsers recognize this setting and so do you.

The new addition is the font property with the -apple-system-body value. This font is the key to getting support for Dynamic Type. This feature has been in WebKit for almost a decade and is fully documented. This property overrides the font-size that was defined in the line above and our page now has a size that matches the system setting for body text.

One unfortunate side effect of the font value is that it also sets the page in the system font. I like San Francisco, but I don’t want it on my blog.

With a hint from Mastodon, it occurred to me that I could override the face with font-family. So I now have the best of both worlds: a size that makes my visitor happy and a font that makes me happy.

One other addition that I made to my CSS was a tweak for desktop browsers. There is no Dynamic Type setting on macOS (yet?!) and the default size was a bit small for my taste. A @media rule fixed that:

@media screen and (min-width: 801px) {
body {
font-size: 1.2rem;
}
}

Now any browser window that’s wider than 800 points will get a slightly larger font.

You can, of course, use any of the other predefined font values, such as -apple-system-headline or -apple-system-footnote, but you’ll also need to override the family with each use.

But it’s likely that you’re already using em and rem sizes so that elements scale correctly in other contexts. By setting the base size in the html element, my rule for headers “just worked”:

.entry-header h1,
.entry-header h2 {
font-size: 1.4em;
...
}

Another important point: if you’re using WKWebView or SFSafariViewController on an Apple platform, it will have the same capabilities as you’ve seen above. This means that you can have dynamic text in a SwiftUI view and a web page that matches exactly. This is why I needed to solve the problem in the first place.

Take a moment to look at your blog, product, or company style sheet and think about how this approach to accessibility can improve things. If you’re like me, in a couple of hours you’ll have a much better site.