Skip to content

Instantly share code, notes, and snippets.

@Origame
Last active September 30, 2016 07:34
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 Origame/a16b60d0a7b499ab421206733e80d9cb to your computer and use it in GitHub Desktop.
Save Origame/a16b60d0a7b499ab421206733e80d9cb to your computer and use it in GitHub Desktop.
JS function to manage CSS classes to set [width 100%; height auto;] or [height: 100%; width: auto;] on images depending on their natural ratio and their container size
setImgSize: function() {
// Get containers size Height and Width)
var containerH = $('.myContainer').height();
var containerW = $('.myContainer').width();
// Get images natural size and calculate ratio:
// if image is wider than the container, class "wide" sets height to 100% and width to auto
// otherwise, class "tall" sets width to 100% and height to auto
$('.image').each(function(){
var thisImg = $(this);
var image = new Image();
image.src = $(this).attr("src");
image.onload = function() {
var scaleW = Math.floor((this.width * containerH) / this.height);
var isTooWide = Math.floor((scaleW > containerW));
if ( isTooWide ){
thisImg.removeClass('tall').addClass('wide');
}
else{
thisImg.removeClass('wide').addClass('tall');
}
};
});
//For "tall" images, add a margin-top negative to center vertically
$('.tall').each(function(){
var thisH = $(this).height();
var containerH = $(this).parent().height(); //replace with actual container
if ( thisH > containerH ){
var topMargin = (thisH - containerH) / 2;
$(this).css('margin-top', '-'+topMargin+'px');
}
});
//For "wide" images, add a margin-left negative to center horizontally
$('.wide').each(function(){
var thisW = $(this).width();
var containerW = $(this).parent().width(); //replace with actual container
if ( thisW > containerW ){
var leftMargin = (thisW - containerW) / 2;
$(this).css('margin-left', '-'+leftMargin+'px');
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment