Zach's solution is best if you can use a bg image for the task, but if you need to use a tag <img>(there are times when it is recommended ), then you need javascript to calculate the aspect ratio of the image and determine if it is more squat or more vertical than the target frame. Then some CSS:
Javascript
var img = document.getElementById('some-image-id')
var aspectRatio = img.clientWidth/img.clientHeight;
if(aspectRatio > (270/180)){
img.style.height = 180
}
else{
img.style.width = 270;
}
This will install
CSS
Finally, to center the larger image inside the wrapper vertically and horizontally, regardless of how you fit:
.wrapper{
position:relative;
display:inline-block;
}
.wrapper img{
position:absolute;
top:-9999px;
right:-9999px;
bottom:-9999px;
left:-9999px;
}
Faust source
share