The majority of web image galleries must load at least two copies of every photo: a small thumbnail and a full-size version. While this approach has its advantages, it has an equal number of annoyances and drawbacks.

My recent exploration of object-fit led me to experiment with using the property to improve image galleries, inspired by the work of Chris Mills. The only downside is that the thumbnail images will appear squished in browsers that do not yet support the property (Firefox and IE).

Markup

The basic markup consists of a <div> surrounding a series of <figure> elements:

<div id="o-gallery">
	<figure>
		<img src="backless.jpg" alt>
		<figcaption>Photograph of a woman in a backless dress</figcaption>
    </figure>
  …
</div>

The CSS

I’m using to distribute the images:

div#o-gallery {
	display: flex;
	justify-content: space-between;
	max-width: 1600px;
	margin: 0 auto;
}
div#o-gallery figure {
	flex: 1;
	max-width: 500px;
	transition: 1s;
	margin: 0;
}

Each image occupies equal width:

div#o-gallery img {
	width: 200px;
	max-height: 200px;
	border: 1px solid;
	object-fit: cover;
	object-position: 0% 0%;
	transition: 1s;
	font-size: 0;
	line-height: 0;
}

object-position

Images with object-fit: cover will be focused on their center; moving them around uses the same principle as positioning . To start the object from its upper left corner we can use object-position:

div#o-gallery img {
	object-position: 0% 0%;
}

When each <figure> element is hovered, it becomes twice as wide as its siblings; the image inside expands to its maximum width and height, with no object-fit applied.

div#o-gallery figure:hover {
	flex: 2;
}
div#o-gallery figure:hover img {
	width: 100%;
	max-height: 700px;
	object-fit: none;
}

Conclusion

As you can see from the example, I’ve also moved around the captions for the images while adding responsiveness; you can find the complete code on CodePen.

Photographs by Feng Yi, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/vEKLeX