Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created December 21, 2012 07:46
Show Gist options
  • Save imzjy/4351287 to your computer and use it in GitHub Desktop.
Save imzjy/4351287 to your computer and use it in GitHub Desktop.
Maximize the image to the whole view port, and also keeping the aspect ratio. Browser compatibility: IE7+, Chrome, Firefox, Safari, Opera
<!DOCTYPE html />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Stimuli</title>
<style type="text/css">
html, body
{
margin:0px;
padding: 0px;
height:100%;
background:#000;
overflow:hidden;
}
#wrapper
{
text-align:center;
}
.maxHeight
{
height:100%;
width:auto;
}
.maxWidth
{
width: 100%;
height: auto;
}
</style>
<script type="text/javascript">
window.onload = function maxImage() {
var elImage = document.getElementById('img-place-holder');
var elViewport = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
var orgImage = new Image();
orgImage.src = elImage.src;
var pvRatio = elViewport.clientHeight / elViewport.clientWidth;
var orgImgRatio = orgImage.height / orgImage.width;
elImage.className = (pvRatio > orgImgRatio) ? 'maxWidth' : 'maxHeight';
if (navigator.appName == 'Microsoft Internet Explorer') {
if (elImage.className == 'maxWidth') {
elImage.width = elViewport.clientWidth;
} else {
elImage.height = (elViewport.clientHeight);
}
elImage.className = '';
}
}
</script>
</head>
<body>
<div id="wrapper">
<img id="img-place-holder" src="http://url-to-image/image.png" alt="Image Place Holder" />
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment