Replacing broken avatar images with background SVG Emoji


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:

CSS CSS.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 SVG<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


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

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

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">