Fixing miss-aligned monospace text in Android browsers
I've recently tried to render some ASCII diagrams like the one below in a tag in HTML. While<br>it looked fine in Neovim and in the MacOS and iOS browsers, I've noticed that on Android the boxes<br>were slightly misaligned.
┌────▼─────┐<br>│ Phase 1 │<br>└────┬─────┘<br>┌────▼─────┐<br>│ Phase 2 │<br>└────┬─────┘
Original: the diagram above should not align on Android devices
┌────▼─────┐<br>│ Phase 1 │<br>└────┬─────┘<br>┌────▼─────┐<br>│ Phase 2 │<br>└────┬─────┘
Fixed: the diagram above should correctly align on Android devices
A Google search showed that this seems to be a common problem, but no solutions was immediately<br>obvious. ChatGPT wasn't able to fix the issue, but it at least pointed in the right direction: Even<br>with a webfont loaded, the browser is most likely falling back to a system monospace font for glyphs<br>that are not available in the (web)font. And for some reason the monospaced system font on Android<br>has a different width, resulting in the misalignment.
Some google searches and multiple different LLMs suggested to load the Noto Sans Mono from Google<br>fonts. This font would have no missing glyphs (at least for the box-drawing glyphs) and so no<br>fallback should occur. However, after embedding the webfont via a simple tag, the<br>miss-alignment persisted. Various others suggested CSS hacks did not fix the problem either. I was<br>about to give up, but then found the discussion on the mkdocs<br>org which mentioned that the file<br>size of the WOFF2 version of Noto Sans Mono is noticeable smaller than the TTF version since many<br>symbols were missing.
Turns out that the font served from Google fongts via is a most likely a trimmed down<br>version. After downloading the .ttf itself and serving it myself, the alignment issue was gone.
Relevant CSS snippet to embed a .ttf directly in CSS:
@font-face {<br>font-family: "Noto Sans Mono";<br>src: url("/path/to/your.ttf");
pre {<br>font-family: "Noto Sans Mono"