Inline links with sticky icons

Icons are great for indicating external/email links or showing file types. When using them, you should always make sure they stick to their text and don’t wrap around on their own. With ↗ glyphs or 🥨 emoji, it’s easy – just put a non-breaking space between text and icon and you’re done. No matter how the text wraps, the icon stays glued to the first or last word.

Most of the time however, you want to use custom SVG icons for full control over color and shape. If you just replace your glyph or emoji with an SVG, the icon can wrap to the next line, looking sad.

Two links with smiley icons, one sad and one happy. The sad link has the icon wrapped to the next line. The happy link has the icon glued to the last word of the text.

But don’t worry, we can make it happy again with a simple solution!

The HTML Structure

All we need to do in the HTML is to wrap the link text in a span and place the SVG icon right next to it. We can handle the spacing in CSS or simply use a non-breaking space between the two elements. This way there’s always exactly one space between text and icon:

<a class="link" href="#">
  <span class="link__text">Link text</span>&nbsp;<svg>...</svg>
</a>

For right-to-left languages or icons before the text, just flip the order:

<a class="link" href="#">
  <svg>...</svg>&nbsp;<span class="link__text">Link text</span>
</a>

The CSS

The trick is in how we handle white-space. Setting nowrap on the link keeps the icon glued to the
text, while normal on the text lets longer text wrap as needed.

.link {
  /* Default */
  display: inline;
  /* Prevent icon wrapping */
  white-space: nowrap;
}

.link__text {
  /* Allow text wrapping */
  white-space: normal;
}

.link__icon {
  /* Default */
  display: inline;
  /* Vertical alignment */
  vertical-align: middle;
}

By default, a and span elements are inline. I’ve added the display: inline for clarity.

After you’re done glueing your icon to the text, feel free to fine-tune the icon position with vertical-align. If you want to get the icon size just right, the cap, ex and lh units are super useful. They are based on the font and scale with the text size.

Want to learn more about these font-based units?
Check out the MDN Web Docs on “Relative length units based on font”.

Interactive example

In this CodePen, you can see how the icon stays glued to the last word of the link text. Resize the wrapper on the bottom right to see how the text wraps and the icon stays happy:

See the Pen Happy sticky icons by Thomas Günther (@medienbaecker) on CodePen.