Created
January 13, 2016 08:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="img-container"> | |
<img src="http://placehold.it/550x800"> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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'); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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