The perfect CSS for Organizational Chart Avatars

The requirement sounded simple; show a user’s photo next to their name. The reality was that some photos were square and some wide while others were very large and some were small. I thought this was a good chance to combine a few code and CSS techniques to see what could be accomplished.

First I started with the image tag, which allowed me to resize all of the images and show missing ones, but it shrinks and squeezes them in ways that don’t look natural. See Squished Joe below. Catching the errors is a great way to show a clean ‘missing photo’ image.

background image in a <div>

Instead, I decided to use a background image in a div giving me control over cropping. Now I can shrink the image to the size I need and crop it nicely. However, I lost the ability to show missing images (no onerror in a div) and I found that I was only getting the left side of wide images. This looked bad when the face was centered. See Only Left Side Joe below.

background-position: center center;

By using the background image and adding background-position of ‘center center’, I can now shrink the image and center the wide images, while still showing them as 80×80 pixels square. Almost perfect except for the missing images. See Face Centered and Al Einstein.

Solving for the missing image

A quick google of the image error issue shows a number of excellent solutions. I choose to use a combination of HTML onerror and javascript by including a hidden image tag inside my div. I have this img tag load the same image, and if it’s a broken link the onerror can correctly set the parent div with my stock missing image using a little javascript/jQuery.

Related Posts

Tech Topics

About the Author

Eric Lubin

Boca Raton, FL
Advisory Engineer @ConstantContact. I have been with CTCT for 5 years. I love discussing software development and innovation, and thinking about how the next innovation can help your small business.