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.
<img src=”image.jpg” height=”80” width=”80” onerror=”this.src=’missing_photo.png’;” />
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.
<div style=”margin: 0 auto; height: 80px; width: 80px;
background-size: auto 80px; background-image: url('image.jpg’);”></div>
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.
<div style=”margin: 0 auto; height: 80px; width: 80px; background-size: auto 80px; background-image: url('image.jpg’); background-position: center center; background-repeat:no-repeat;”></div>
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.
function on_error(_this) {
$(_this).parents('.crop').css('background-image', 'url(missing_photo.png)');
}
<div class="employee">
<div class="crop"><img class="hidden" src="image.jpg" alt="" />
</div>
John Doe
</div>
Last but not least, I checked it out in IE and found no support for background-size attribute. Adding a ‘scale’ filter fixed that issue:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=image.jpg', sizingMethod='scale');">
My image gallery is complete and code samples can be seen in this fiddle (http://jsfiddle.net/45Wz7/) Let me know what you think! How do you creatively display your avatars?
Leave a Comment