views:

36

answers:

2

This isn't really a question, just something I struggled with on my own and thought others might appreciate a solution.

If you try to apply a border and rounded border radius to a div containing an image in FireFox, you get rounded div borders with a square image sticking out at the corners--rather unsightly.

Solution?

  1. Apply a desired border to the div in css as usual.

  2. Apply a class to the div (in order to work with multiple images: you could use an id instead).

  3. Use jQuery to get the contained img's src attribute.

  4. Set the div background to the aforementioned src value.

  5. Apply the border radius.

  6. Hide the img itself to reveal the background behind it.

And wallah:

$('.imgDiv').each(function(){
    var imgSrc = $(this).children().attr('src');
    var imgBg = 'url(' + imgSrc + ')';
    $(this).css('background-image', '' + imgBg + '').css('-webkit-border-radius','15px').css('border-radius','15px').css('-moz-border-radius','15px');
    $(this).children().hide();
});

Now the image will appear with rounded corners and a border. With JavaScript disabled, users will still see the image with a border, albeit totally square. And the only markup needed in the HTML is the new class applied to the div.

+1  A: 

If you're too specific about javascript disabling . the only alternative is CSS.

CSS

.imgDiv {
   -webkit-border-radius : 15px;
   border-radius : 15px;
   -moz-border-radius : 15px;

 }
Ninja Dude
A: 

In Firefox 4, you'll get rounded borders on an img with just:

img { border-radius: 15px }
David Baron