Preventing Icon Wrap After Text

I’ve got text. I’ve got an icon at the end of the text. When the container shrinks, the icon wraps to the next line. That orphaned icon is kind of lonely. What if we could get the icon to bring a friend with it?

(This felt like something that should be really easy and has been solved a million times before. And yet, I couldn’t find anything written up on this and, well, I needed it. So here we are.)

A trick I’ve used in the past to prevent orphaned words was to add a non-breaking space ( ) between the last two words. This forces them onto a line together.

Adding a non-breaking space between text and an image, however, doesn’t work. The image (or an element set to inline-block) creates a boundary, allowing the image to break onto a line all by itself.

Thus, we need to put the image into a container and force that container to stick together.

Wrapping the last word

... <span>word<img/></span>

If we have control over the HTML, we can wrap the last word and the image together and then use a couple different techniques to keep the two together.

display: inline-block;

If we wrap the text and the image together using inline-block then the items will be treated as an unbreakable container.

white-space: nowrap;

Alternatively, we can use nowrap to prevent wrapping. This second technique is important as we’ll need this for the other techniques.

Templates

With template-driven content, we usually don’t have the ability to grab the last word and wrap it. However, we can put things beside it.

... word<span>&nbsp;<img></span>

We can’t just put the image next to the word, though. We need a non-breaking space. This prevents the word and the space from breaking. And the wrapped element uses nowrap to prevent the space and the image from breaking. This allows the word and the image to stick together.

This also works if we need the text to be wrapped in an element and still place the image beside it.

... word</span><span>&nbsp;<img></span>

The key is that there is no space between the closing tag of the text and the opening tag of the space/image combo.

No space

Finally, if you don’t want a space, you can use the zero-width non-breaking space: &#65279;.

... word</span><span>&#65279;<img></span>

And that’s it! Check out the Codepen.

Published July 12, 2018
Categorized as HTML and CSS
Short URL: https://snook.ca/s/1126