📝 CSS-Tricks 253: 25 years of CSS, CSS font descriptors, and nth-letter woes

View this newsletter on the web.

[Robin]: Earlier this week I stumbled upon a problem where the only solution I could think of was a hypothetical one: an :nth-letter selector in CSS. It would work something like this:

.element:nth-letter(2) { color: red; }

Similar to :nth-child, the CSS above would make the second letter in that word red. Yet, today no such thing exists, unfortunately. A while back Jeremy Keith wrote why he believes :nth-letter would be so darn useful and you’ve likely experienced this limitation, too. One common example is when you want to edit big display titles on a website, let’s say something like this:

Imagine we want to change the color of each of these letters in this word. Perhaps the best solution would be to make it an SVG or to wrap each letter in a span like this:

<h1> <span>r</span> <span>a</span> <span>i</span> <span>n</span> <span>b</span> <span>o</span> <span>w</span> <span>!</span> </h1>

Pretty gross, right? It’s a shame that we have to mess up the markup simply to make a relatively simple aesthetic change.

Since we’ve been so very lucky with properties in CSS, I feel like this is now at the top of my CSS wishlist. It’s one of the few remaining challenges that have stuck around in web development since before I started and fixing it would help us make micro-typographic changes to the characters in a word or in a paragraph whilst encouraging folks to think about text in a different way on the web.

[Chris]: Ten years ago (2011), I wrote A Call for ::nth-everything. Not just letters, but words and lines too. Maybe even sentences. Wondering about use cases? Well, anything that uses Splitting.js for one (here’s a collection of demos).

Last I heard, I think the danger/pushback on all this is other languages. Like, there are some languages where one character also represents a word or phrase, so how do you design a feature like this that isn’t too biased toward English, and similarly-featured languages?

I believe the danger of the <span>s that Robin posted above is that screen readers (some, anyway?) read each of those characters with pauses in between, rather than just speaking “rainbow.” So, if you really want to do that to get the style, maybe try:

<h1> <span class="visually-hidden">rainbow</span> <span aria-hidden="true"> <span>r</span> <span>a</span> <span>i</span> <span>n</span> <span>b</span> <span>o</span> <span>w</span> <span>!</span> </span> </h1>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s