CSS / Javascript image size to fit and maintain aspect ratio

I have a 180x270 block that should display images

Image sizes can vary, and I want it to expand or decrease so that the smaller border (height or width) matches the block, while the larger border is cropped while maintaining the aspect ratio.

Examples are: - A 360x600 image resizes to 180x300, and I crop a height from 300 to 270 - A 100x135 image resizes to 200x270, and I crop a width from 200 to 180

Basically I want to make sure that there is no free space when I expand / reduce the image while maintaining the proportions, trimming the section that exceeds the block

Any suggestions on css or javascripts that can handle this?

+4
source share
2 answers

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

//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 height equal to the target frame 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 width
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;
}
+2
source

It seems that you are looking for background-size:coverwhich works when the imagebackground-image

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

Demo

+3

Source: https://habr.com/ru/post/1527218/


All Articles