Last active
December 17, 2015 04:59
-
-
Save thealscott/e2d11731e6eec91c4f8a to your computer and use it in GitHub Desktop.
Center a fullscreen image of any aspect ratio
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
function centerImage() { | |
$img = $('img'); | |
var newimage = new Image(); | |
var originalImageWidth; | |
var originalImageHeight; | |
newimage.src = $img.attr('src'); | |
newimage.onload = function() | |
{ | |
// resize/reposition image based on aspect ratio relative to viewport aspect to make sure it is always fullscreen and centered | |
originalImageWidth = this.naturalWidth; | |
originalImageHeight = this.naturalHeight; | |
var imageAspect = originalImageWidth / originalImageHeight; | |
var windowAspect = $(window).width()/$(window).height(); | |
if (windowAspect > imageAspect) { | |
$img.width($(window).width()).height('auto'); | |
// shift the element up | |
var height = $img.height(); | |
var shift = (height - $(window).height()) / 2; | |
if (shift < 0) shift = 0; | |
$img.css({ | |
"top" : -shift, | |
"left" : 0 | |
}); | |
} | |
else { | |
$img.height($(window).height()).width('auto'); | |
// shift the element left | |
var width = $img.width(); | |
var shift = (width - $(window).width()) / 2; | |
if (shift < 0) shift = 0; | |
$img.css({ | |
"left" : -shift, | |
"top" : 0 | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment