Skip to content

Instantly share code, notes, and snippets.

@stephenscaff
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save stephenscaff/9833232 to your computer and use it in GitHub Desktop.

Select an option

Save stephenscaff/9833232 to your computer and use it in GitHub Desktop.
Turn img to a background-image of it's parent div. Great for accessing the proportional cropping of bgs while still droppin some meaningful markup.
//Parent div
$('.js-tobg').each(function() {
//Hunt down img in parent div and snag its src
var imageUrl = $(this).find('img').attr('src');
//Now add inline style with backgroud-image to div
$(this).css('background-image', 'url(' + imageUrl + ')');
//Maybe cover the badboy?
$(this).css('background-size', 'cover');
//Visually hide the img tag if you want the div to maintain aspect ratio
$(this).children("img").css("visibility", "hidden");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment