Skip to content

Instantly share code, notes, and snippets.

@jamesmfriedman
Last active December 22, 2015 02:59
Show Gist options
  • Save jamesmfriedman/6407114 to your computer and use it in GitHub Desktop.
Save jamesmfriedman/6407114 to your computer and use it in GitHub Desktop.
A little utility for creating responsive centered images while still using an img tag. Basic premise, the image size is controlled by the padding value in css, while the real image is set to 0 by 0.
img.responsive-image {
padding: 50%; /*controls the ratio of the image. 37.5% 50% would be a 4 x 3 image*/
width: 0;
height:0;
background-size: cover;
background-position: center center;
}
/**
* Quick little utiltiy that makes an image responsive by changing it to a background photo
* Just add class of 'responsive-image'
*/
$(function() {
var __init__ = function() {
$('.responsive-image:not(.responsive-image-fixed)').each(function(){
var img = $(this);
img.addClass('responsive-image-fixed');
img.attr('style', 'background-image: url('+ img.attr('src') +');');
});
}
__init__();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment