Container query width

25–

Testing, cause

Some people on Twitter were testing my website, and found that some articles didn’t scale well on a smartphone held in portrait position, even when no images are involved. I found that this was caused by code fragments or extracts from log files, which I formatted using <pre>, and sometimes using <code>.

In the presence of a CSS max-width setting, running text can adapt to the horizontal screen width by adding more line wrapping points, so that fewer words fit on a text line. However, with code lines, this is impossible, because they already have their own, inten­tional line wrapping, which should stay intact. Then, it seems to me, the only way to make them fit in a smallish screen width, is to vary the font size.

Solution

Looking for solutions I found a page or pages which I failed to note, so I cannot reproduce any hyperlinks here. I do remember what I learned: a recent (2022) addition to CSS is that you can use units like vw and vh, by which you can size things, including fonts, as a percentage of size of the viewport. So 3vw means three percent of the current viewport’s width. Likewise 3vh refers to the viewport’s height.

I experimented with that, but it didn’t produce acceptable results in my situation. Yet there’s more: cqh and cqw refer to the height and width of a containing element. That worked for me. So in my central CSS file ../css/textfont.css" I added:
container-type: inline-size;
for my class rh-article-noad, which, now that I no longer have Adsense ads on my site, is the class of the <div> I use for the main text of nearly all of my articles. Then there’s the default setting pre {font-size: 3cqw;} .

That is adequate in most cases. Where it isn’t, I deviate from the default either in a
<style>…</style>
block in the <head> of a page, or individually for each preformatted bit of text, as follows:
<pre style="font-size: 2.2cqw;">, for example.

Examples

Examples of web pages where I used cqw:

Evaluation

Depending on the circumstances, the code fragments are sometimes in rather large type, and sometimes too small to be properly read. Then zooming in makes the text extend over the screen width, again confronting us with the need to scroll horizontally, which was what we were trying to eliminate in the first place. But such is life, I cannot think of a better solution right now.

Solved

24 September 2025, 10:30B