Prevent component orphans with text using CSS

Across this website, you’ll see badges and some of these badges are attached to text. One of the annoying side effects I started seeing late into the design during mobile revisioning was weird, broken badges: as the container condensed, it would cause elements, such as div, span, or an img, to break into new lines, pushing my labels at the start of the next line and causing a cruddy overhang.

Boo Ugly.

As you can see, this can be particularly unsightly when combined with some tight layouts and it would take some challenging CSS to make look normal. My solution? Attach it to the last word.

The solution

In a perfect world, we’d be able to wrap the final word in a span and use simple CSS to prevent breaking of the two apart:

<h2>Saint Louis <span>Makes<tag \></span></h2>
span { 
    white-space: nowrap;
}

but the content in the blog is entirely dynamic, and using PHP to wrap header tags on output, while possible, was unfeasible.

The key: the non-breaking zero-width character &#65279; to join more characters together in a span that is no-wrapped. Instead, we can format out HTML output like this:

<h2>Saint Louis Makes<span>&#65279;<tag \></span></h2>

The key is the lack of space between the two word components, which with white-space: nowrap; will pull the last word to the next line with the badge as one combined unit.

That’s it! Everything looks much better now:

I am Dan Griffin and you can find me on Mastodon
CSS

The Blog

Base & Elevated System (and Grouped!) Background Colors

In iOS 13, Apple introduced a slew of new colors that are also dynamic – meaning they will adjust between light and dark modes (and other scenarios, such as high contrast). Of the new colors, the various background colors are pretty pecular: iOS defines two sets of background colors—system and grouped—each of which contains primary,…

iOS iOS 13

Always Taking Inquiries

At the moment I am not taking on many new projects, but am still available for inquiry or questions.

Reach Out To Dan