Use CSS3 background-size
together with no-repeat center center
(demo).
#image_wrapper {
height:120px;
width:100px;
background:no-repeat center center url(image.png);
background-size:contain;
}
#image_wrapper > img {
display:none;
}
If you want to use JavaScript try:
<style>
.image_wrapper {
height:190px;
width:1000px;
border:1px solid;
background:no-repeat center center;
background-image:url(science.png);
background-size:contain;
}
</style>
<script type="text/javascript">
function getStyle(el,cssAttribute){
if(window.getComputedStyle)
return window.getComputedStyle(el, "").getPropertyValue(cssAttribute);
else if(document.getElementById(strID).currentStyle)
return document.getElementById(strID).currentStyle.getAttribute(cssAttribute,false);
else
return el.style.getAttribute(cssAttribute,false);
}
window.addEventListener("DOMContentLoaded",function(){
var w;
for(var i = 0; w = document.querySelectorAll(".image_wrapper")[i];++i){
var backgroundSize = '';
if(w.firstChild.width < parseInt(getStyle(w,"width")))
backgroundSize += 'auto ';
if(w.firstChild.height < parseInt(getStyle(w,"height")))
backgroundSize += 'auto ';
if(backgroundSize === '')
backgroundSize = 'contain';
w.style.backgroundSize = backgroundSize;
w.style.backgroundImage = 'url('+w.firstChild.src+')';
w.firstChild.style.display = 'none';
}
},true);
</script>
This will change every <div class="image_wrapper"><img src="..."/></div>
to a fancy image wrapper.