Most browsers do not allow images to be cropped using CSS3’s border-radius
. Tim Van Damme recently posted a workaround for this issue. It’s a nice trick, and doesn’t require JavaScript.
It does, however, require an extra span
to be added to the page’s markup, which is quite a pain to manually apply to each image. Bram Van Damme (no relation to Tim) posted a simple jQuery script that automate’s Tim’s workaround with minimal effort. It’s a perfect example of using JavaScript for progressive enhancement purposes, as the page is still usable when JavaScript and/or CSS is disabled.
Being a MooTools kind of guy, I decided to whip up a MooTools-flavored version. Enjoy!
window.addEvent("domready", function (){
$("img").each(function(img){
new Element("span", {
"class": "rounded",
styles: {
"background-image": "url(" + img.getProperty('src') + ")",
height: img.getProperty('height') + "px",
width: img.getProperty('width') + "px"
}
}).wraps(img);
});
});
Code language: JavaScript (javascript)
Bear in mind this JavaScript relies on your page having some pre-defined CSS:
.rounded {
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
display: block;
}
.rounded img { opacity: 0; }
Code language: CSS (css)
Notes:
- The demo page has the code wrapped in a function, which makes the code reusable; it accepts any CSS selector, such as “img”, “#myid img”, “p img”, “img.rounded”, etc.
- This will only work in browsers that support CSS3
border-radius
, which means no IE6/7/8 or older versions of Safari, Firefox, or Opera.
Comments
Kjetil Engen wrote on November 19, 2010 at 12:24 am:
Hi,
Thank you for a great script. I'm trying to use this on a Joomla site, but can't get it to work… I copied everything from your example, but the image does not get rounded corners. Do you have any tips?
philip wrote on November 22, 2010 at 9:59 am:
@kjetil nope, i haven't tried it with Joomla, sorry. all i can suggest is to get it working in a simple page first, then move it into your Joomla site. if it worked in the simple page but not the Joomla page, there may be some kind of conflict (either JS or CSS) in the Joomla code. at that point you just have to walk through the code with a fine-tooth comb looking for possible causes.
Hi,
Thank you for a great script. I’m trying to use this on a Joomla site, but can’t get it to work… I copied everything from your example, but the image does not get rounded corners. Do you have any tips?
@kjetil nope, i haven’t tried it with Joomla, sorry. all i can suggest is to get it working in a simple page first, then move it into your Joomla site. if it worked in the simple page but not the Joomla page, there may be some kind of conflict (either JS or CSS) in the Joomla code. at that point you just have to walk through the code with a fine-tooth comb looking for possible causes.