Carl Bembridge
Carl Bembridge

Reputation: 397

Fit images (both landscape and portrait) into square thumbnail

I'm really struggling to get images that are both landscape and portrait orientation to fit nicely into a square thumbnail for the purpose of a gallery.

I've tried a variety of CSS tricks but think i need to maybe use Javascript.

Anybody have any idea how i could solve this?

EDIT - the HTML/CSS can be anything, at present it simply prints out images with a class of thumb-square, ie.

<img class="thumb_square" src="/images/uploads/pic.jpg"/>
<img class="thumb_square" src="/images/uploads/pic2.jpg"/>
<img class="thumb_square" src="/images/uploads/pic3.jpg"/>

Upvotes: 4

Views: 8645

Answers (2)

Nahn
Nahn

Reputation: 3256

I think this is exactly what you need: No matter how big the images are, you will see the whole height (if landscape), or width (if portrait);

jFiddle: http://jsfiddle.net/ECRc4/3/

HTML:

<div class="thumb" style="background-image: url('http://placehold.it/250x500')"></div>
<br/>
<div class="thumb" style="background-image: url('http://placehold.it/500x200')"></div>
<br/>
<div class="thumb" style="background-image: url('http://placehold.it/100x200')"></div>

CSS:

.thumb{
    display:inline-block;
    width:100px;
    height:100px;
    background:center;
    background-size:cover;
}

Upvotes: 4

poplitea
poplitea

Reputation: 3737

One possible solution (tested): Display each thumbnail in a div. Show the thumbnail using the css background property, and center with no-repeat. You must specify the width and height of the containing div. Set the width and height to the maximum width/height of all your thumbnails. I.e. if your thumbnails are 150px*200px and 200px*150px, set all divs to be 200px*200px. The thumbnails will then be centered within a 200px*200px box, regardless if they are in portrait or landscape "mode".

Example:

<div style="width:200px; height:200px;
   background: url('/images/uploads/pic.jpg') no-repeat center;
   border:1px solid red;">
</div>

<div style="width:200px; height:200px;
   background: url('/images/uploads/pic2.jpg') no-repeat center;
   border:1px solid red;">
</div>

<div style="width:200px; height:200px;
   background: url('/images/uploads/pic3.jpg') no-repeat center;
   border:1px solid red;">
</div>

Upvotes: 6

Related Questions