Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make same sized thumbnails

I'm having a hard time now trying to make same sized thumbnails, I have a simple gallery script that just takes all images out of database and places them to the page with max width 150px and max height 150px.

Now , it looks weird because all images have different shape, is there any way to make them same size without breaking the image apart? The simplest way possible please. I don't want to have an option on uploading step to chose dimensions for thumbnail.

like image 868
EvilNabster Avatar asked Dec 13 '14 14:12

EvilNabster


1 Answers

With img you only have two options: Set a maximum width, or a maximum height. Either way you won't get reasonably-sized thumbnails: If you set the maximum width, then some images will be too tall. If you set the maximum height, then some images will be too wide. If you set both width and height, it'll get horribly distorted, because it will ignore the aspect ratio.

Instead, I suggest making a div of a fixed size and setting the thumbnail as its background-image, then setting background-size to cover. This will give much better thumbnails, as it scales and crops the image to make it fit. If you want to avoid cutting off the image's edges, give the div a background-color and set background-size to contain, which instead scales down the image to make it fit and creates a "letterbox" effect.

Putting it all together (plus thumbnail centring for the crop, and inline-block so it acts like an <img> tag does):

<style>
.thumbnail {
    background-color: black;
    width: 250px;
    height: 200px;
    display: inline-block; /* makes it fit in like an <img> */
    background-size: cover; /* or contain */
    background-position: center center;
    background-repeat: no-repeat;
}
</style>
<div class=thumbnail style="background-image: url(image1.jpg);"></div>
<div class=thumbnail style="background-image: url(image2.jpg);"></div>

Here's a jsfiddle demo for cover: http://jsfiddle.net/tbeog5o9/24/

And here's a jsfiddle demo for contain: http://jsfiddle.net/tbeog5o9/25/

like image 191
Andrea Avatar answered Nov 02 '22 16:11

Andrea