How to Bind Icons to the Last Word of Inline Text

2018-05-31 | #css, #solution, #webdev

In screen designs for websites you'll often have the situation of a trailing icon attached to the end of an inline text. For example: let's imagine a teaser, which has a title, followed by a little arrow, telling the user there's something to click on. The arrow is always the last character in the title, moving from line to line when then text gets longer.

This seems fairly simple, doesn't it? This is a classical case of mistaken simplicity, since this opens up several problems challenging the way CSS handles texts.

1. Putting an icon into an inline text most likely will increase the line-height of the line the icon is in, since it needs a bigger font size than the copytext. This leads to a very ugly jump in line-height, that you'll notice right away.

2. When the text wraps on responsive layout, you'll not want the icon to wrap alone to the next line, but always "stick" to the last word. If there's no space between the word and the icon, this is simple, but most times there's a padding/offset to be implemented. How is that gonna work in an line text?

3. You'll additionally still want the icon to be part of the normal text flow, following the last character directly and not being positioned absolutely in a corner of the text holder.

Here's what I came up with to solve this, which, to my knowledge, works everywhere from IE11 upwards (did not test anything below).

Let's take this markup:

<span class="title"><span class="text">I'm a teaser title!</span><span class="icon"></span></span>

With this styling:

.title {

display: block;

> .text {

padding-right: 25px;

}

> .icon {

position: relative;

@include icon(arrow-right, after);

&:after {

position: absolute;

right: 0;

font-size: 20px;

line-height: 1.0;

}

}

The important thing here is to use two separate inline elements (the spans) without ANY whitespace between them and use the second one, being inline and having the same font settings as the title itself but having no dimensions as a relative positioned holder for the icon, to be positioned absolutely, so it does not disturb the line height. The missing space between the spans glues the icon to the last word.

But how do we add the offset just to the last line? Well, it turns out you can actually set a padding-right on an inline text, which magically only effects the last line, which actually makes sense if you think about it: an inline element is essentially one long element snaking down a container, its only relevant height being the line-height. To a padding should, since the element wraps and is not a block, only take effect at the end. And thats exactly what happens. So you can define a padding-right for the text wide enough to hold the icon itself + the offset you want to leave to the text.

And voila: sticky, non-disturbing inline icon with an offset.