A CSS-only Avatar Fallback with Cross-Browser Compatability
13 August 2024

A CSS-only Avatar Fallback with Cross-Browser Compatability

A previous post I made described how to build a CSS-only fallback for avatar image. Since that original post, I’ve learned that not all browsers treat broken image links the same. Thus, my original solution is not fully cross-browser compatible. So here I am, sharing my new solution for a CSS-only avatar fallback!

This solution utilizes the HTML <object> element, and it fairly straight-forward. <object> elements will display the data source, if available, and then will fallback to whatever is inside the <object> tags when it isn’t, in our case, the user’s initials.

First you’ll need the <object> element with the appropriate attributes and the user’s initials placed inside it.

<object 
  type="image/gif" 
  class="avatar" 
  data="https://thispersondoesnotexist.com/1"
  aria-label="Sandy Sanderson Profile Photo">
    <div class="avatar__initials">SS</div>
</object>

Next, you need the stylesheets to make your object look more like an avatar, or user profile picture.

.avatar {
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 4rem;
  width: 4rem;
  overflow: hidden;
  position: relative;
  vertical-align: middle;
}

.avatar__initials {
  background-color: purple;
  border-radius: 50%;
  color: white;
  display: flex;
    align-items: center;
    justify-content: center;
  font-family: monospace;
  font-size: 1rem;
  font-weight: bold;
  height: 100%;
  letter-spacing: 1px;
  position: absolute;
    left: 0;
    top: 0;
  width: 100%;
}

And there you have it! An updated CSS-only fallback for your avatars. Let me know what you think!

See the Pen HTML/CSS only Avatar with Fallback by Katie Pohlman (@kspohlman) on CodePen.

Related Posts

Want to learn more about the work we do?

Explore our work

Ready to start your software journey with us?

Contact Us