Skip to content

Instantly share code, notes, and snippets.

@marcofugaro
Created January 13, 2016 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcofugaro/0e784fea3a1a006b3b92 to your computer and use it in GitHub Desktop.
Save marcofugaro/0e784fea3a1a006b3b92 to your computer and use it in GitHub Desktop.
`background-size: cover` and `background-position: center center` on img element with jQuery
<div class="img-container">
<img src="http://placehold.it/550x800">
</div>
$(window).on('load resize', function() {
$('.img-container').each(function() {
var $img = $(this).children('img');
var $container = $(this);
var imgHeight = $img.outerHeight();
var imgWidth = $img.outerWidth();
var imgRatio = imgWidth / imgHeight;
var containerHeight = $container.outerHeight();
var containerWidth = $container.outerWidth();
var containerRatio = containerWidth / containerHeight;
//background-size: cover
if(imgRatio > containerRatio) {
$img.addClass('expand');
imgHeight = $img.outerHeight();
imgWidth = $img.outerWidth();
} else {
$img.removeClass('expand');
}
//background-position: center center
$img.css('top', ((- imgHeight / 2) + (containerHeight / 2)) + 'px');
$img.css('left', ((- imgWidth / 2) + (containerWidth / 2)) + 'px');
});
});
.img-container {
position: relative;
}
img {
width: 100%;
height: auto;
&.expand {
width: auto;
height: 100%;
}
position: absolute;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment