Rounded Corners for Images with CSS 3 and jQuery
Rounded corners with border-radius is one of the most used CSS 3 enhancements, but it doesn’t reliably work on images. There’s a way around that, however. That’s what this tutorial is about. I didn’t invent this general technique, but the few examples I’ve found were either too messy or failed to work with linked images.
Ok then, let’s start with an image from a parking garage near me:

Let’s first try the easy way of adding border-radius styles to the image itself:

Those of you using Webkit browsers (excluding Mobile Safari) will see rounded corners. The rest of you will likely see no change at all. Even if we have it believe it is a block-level element, it still doesn’t work. What we’re going to do is create a new element, round its corners, and set its background to the original image.
First let’s define a basic CSS class for any image we want to apply rounded corners to.
.roundedimage {
display: inline-block;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}
And the script to do the work of converting the image.
$(document).ready(function() {
$(".roundme").each(function() {
$(this).one("load",function() {
var url = $(this).attr("src");
var imageHeight = $(this).height();
var imageWidth = $(this).width();
$(this).css("visibility", "hidden");
$(this).wrap('');
$(this).parent()
.css("width",imageWidth)
.css("height",imageHeight)
.css("background-image","url("+url+")");
});
if (this.complete) $(this).trigger('load');
});
});
This script looks for anything with classname “roundme” and assigns a function to run when it is loaded. This function stores the source location and dimensions of the image, turns the visibility off, and wraps it with a span. This new wrapper element is then given the image’s dimensions and source URL for its background.
Some browsers do not fire the load() function if the image has been cached. This is a problem which would cause the whole technique to fail. The this.complete statement at the end addresses this issue. To prevent the load() function from potentially executing twice, all we need to do is make sure to attach the load() event handler using the one() method (it’s just like bind() only it automatically unbinds itself right after it runs the first time).
Now we just attach the “roundme” class to any image we want rounded for all browsers:
The jQuery above transforms this into:

Rad. But, what if the image is linked?
It’s cool. We wrapped it in a span so it’s still valid — hooray! I’ve already found a use for this for an upcoming mobile launch of Coolspotters.com. Hopefully others can benefit as well.


































