Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS scale and square center crop image

So I have a collection of thumbnails in my app, which is the size of 200x200. Sometimes the original image doesn't have this ratio so I am planning to crop this image to a square.

Currently it just streches the image to fit into the thumbnail, so say my original image size is 400x800, then the image looks very squished. I wanted to crop this image so it looks at the shortest width/height and then crop it to a square, so in my example above it will be cropped to a 400x400.

Is there a way to easily do this via CSS or do I have to use some sort of JS to do this?

like image 415
adit Avatar asked May 01 '13 00:05

adit


People also ask

How do I crop an image to the same size in CSS?

Using object-fit The object-fit CSS property can be used to easily crop images. It can have five values, but cover is the most suitable. By setting object-fit: cover; , the aspect ratio of the image is preserved while still fitting into the size of its content box.


1 Answers

You can do this easily in CSS if you use background-image.

.thumb {     display: inline-block;     width: 200px;     height: 200px;     margin: 5px;     border: 3px solid #c99;     background-position: center center;     background-size: cover; } 

In this fiddle, first image is 400x800, second image is 800x400:

http://jsfiddle.net/samliew/tx7sf

like image 70
Samuel Liew Avatar answered Oct 05 '22 13:10

Samuel Liew