Replacing broken avatar images with background SVG Emoji

by @edent | , , | 1 comment

When someone on Twitter mentions my blog, the WordPress WebMentions plugin automatically fetches those Tweets and turns them into comments on the blog post. It looks something like this:

Matt's smiling face.

That is pretty cool - but has one slight problem. If someone changes their Twitter avatar, or deletes their account, the image disappears and I'm left with a broken image.

A broken image.

Booo!

So, how do we fix this? With the awesome power of SVG and Emoji!

As pointed out by Lea Verou, SVGs can contain Emoji. Which makes them easy to use for favicons:

This can also be used with CSS's background property:

.avatar {
  background: url("data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.85em%22 font-size=%22100%22>🗣</text></svg>");
}

That's just a URl encoded version of:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <text y=".85em" font-size="100">🗣</text>
</svg>"

The background image shows up before the contents of the <img> element have loaded. If the src is missing, your users will see this instead:

An emoji instead of an avatar.

Nifty!

You can see it in action here:

There are a few downsides with this approach:

  • Transparent images will show the SVG underneath them.
  • Not every system renders emoji in the same way.
  • Sizing of text within an SVG can be inconsistent.
  • A "broken image" icon might display in the foreground.

Enjoy!

Further Reading

One thought on “Replacing broken avatar images with background SVG Emoji

  1. Beko Pharm says:

    Doing the same @edent – just less fancy: background-image: url('/wp-content/plugins/semantic-linkbacks/img/mm.jpg'); background-size: contain;

Leave a Reply

Your email address will not be published. Required fields are marked *