Last active
August 29, 2015 14:19
-
-
Save heathcliff/2d7c0e5432d301a16f2b to your computer and use it in GitHub Desktop.
Image Cover
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
/* | |
See JSFiddle for combined HTML/CSS/JS | |
http://jsfiddle.net/66c43ao1/ | |
*/ | |
$('.cover').each(function() { | |
var containerHeight = $(this).height(), | |
containerWidth = $(this).width(), | |
image = $(this).children('img'), | |
imageHeight = image.attr('height'), | |
imageWidth = image.attr('width'), | |
newHeight = imageHeight, | |
newWidth = imageWidth; | |
if (imageWidth < containerWidth) { | |
// if the image isn't wide enough to cover the space, scale the width | |
newWidth = containerWidth; | |
newHeight = imageHeight * newWidth/imageWidth; | |
} | |
if (imageHeight < containerHeight) { | |
// if the image isn't tall enough to cover the space, scale the height | |
newHeight = containerHeight; | |
newWidth = imageWidth * newHeight/imageHeight; | |
} | |
var marginLeft = (newWidth - containerWidth)/2; | |
var marginTop = (newHeight - containerHeight)/2; | |
image.css({ | |
marginLeft : '-' + marginLeft + 'px', | |
marginTop : '-' + marginTop + 'px', | |
height : newHeight, | |
width : newWidth | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample HTML
Sample CSS