When working on my photo album thumbnail navigation for this site, I wanted a way to show a square thumbnail of a photo, centered and cropped from the original version. I wanted this to work without pre-rendering a square version on the server, and without using background image tricks.
I found a great technique for doing exactly this at jonathannicol.com/blog/2014/06/16/centre-crop-thumbnails-with-css, adapted from the WordPress media library. The code below is modified slightly from this example.
Markup
<div class="album-thumbnails">
<a href="photo-1.jpg">
<img src="photo-1.jpg">
</a>
<a href="photo-2.jpg">
<img src="photo-2.jpg">
</a>
</div>
CSS
.album-thumbnails a {
/* set the desired width/height and margin here */
width: 14%;
height: 88px;
margin-right: 1px;
position: relative;
overflow: hidden;
display: inline-block;
}
.album-thumbnails a img {
position: absolute;
left: 50%;
top: 50%;
height: 100%;
width: auto;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
.album-thumbnails a img.portrait {
width: 100%;
height: auto;
}
For my use, I am showing a series of 7 square thumbnails on one line, so I set the width to 14% (about 1/7) so that they will fit on one line. Since the width of my container is about 620px wide, I set the height to a fixed amount, 88px, so that the thumbnails will be approximately square.
The neat thing about this is that when the container shrinks when viewed on smaller devices, the widths of the thumbnails will shrink as well. This does mean the thumbnails will no longer be square on narrow screens, but I'm okay with that result. You can also use a fixed pixel height and width if you don't want them to shrink at all.
Javascript
You may notice that the last CSS rule requires a class of "portrait" on image tags where the image is portrait orientation. You can either add that class server-side, or use the Javascript below to add the class when viewed.
document.addEventListener("DOMContentLoaded", function(event) {
var addImageOrientationClass = function(img) {
if(img.naturalHeight > img.naturalWidth) {
img.classList.add("portrait");
}
}
// Add "portrait" class to thumbnail images that are portrait orientation
var images = document.querySelectorAll(".album-thumbnails img");
for(var i=0; i<images.length; i++) {
if(images[i].complete) {
addImageOrientationClass(images[i]);
} else {
images[i].addEventListener("load", function(evt) {
addImageOrientationClass(evt.target);
});
}
}
});