Ian Lin
Ian Lin

Reputation: 384

CSS/Javascript image size to fit while cropping and preserving aspect ratio

I have a block that is of size 180x270 that I need to show images

The image sizes can vary, and I want to make sure it expands or shrink so that the smaller border (either height or width) matches the block, whereas the larger border gets cropped while preserving aspect ratio.

Examples are the following: - An image of 360x600 gets resized to 180x300, and I crop the height from 300 to 270 - An image of 100x135 gets resized to 200x270, and I crop the width from 200 to 180

Basically I want to make sure there's no white space as I expand/shrink the image while preserving aspect ratio by cropping the section exceeding the block

Any suggestions on css or javascripts that can handle this?

Upvotes: 4

Views: 1471

Answers (2)

Faust
Faust

Reputation: 15394

Zach's solution is best if you can use a bg-image for the task, but if you need to use an <img> tag (there are cases when this is advised), then you need javascript to calculate the image's aspect-ratio and determine whether it is more squat or more vertically stretched than the target frame. Then there's a little CSS as well:

JavaScript

//obtain a dom-reference for the image using getElementById
//or by some other means depending on what you know of its HTML
var img = document.getElementById('some-image-id') 


var aspectRatio = img.clientWidth/img.clientHeight;

//if the img is more squat, set it's height equal to the target frame's height
if(aspectRatio > (270/180)){
    img.style.height = 180 //image is
}
//otherwise the image is more vertically stretched
// so set the img width equal to the target frame's width
else{
    img.style.width = 270;
}

This will set the

CSS

Finally, to center an over-sized image inside a wrapper vertically and horizontally, regardless of how the fit was made:

.wrapper{
    position:relative;
    display:inline-block; 
}
.wrapper img{
    position:absolute;
    top:-9999px;
    right:-9999px;
    bottom:-9999px;
    left:-9999px;
}

Upvotes: 2

Zach Saucier
Zach Saucier

Reputation: 25944

It seems like you're looking for background-size:cover, which works when the image is a background-image

background:url(imgurl.jpg) /* Other background image properties */;
background-size:cover;

Demo

Upvotes: 3

Related Questions