Cropping Image Thumbnails with SVG
Our friend Aaron Parecki recently blogged about a technique he used for centering and cropping image thumbnails using CSS. It’s a clever technique used by WordPress (and many others), but it requires a containing element with explicit dimensions, making it less than ideal for responsive design.
Using SVG, we can make a cropped image that still acts like an image. No CSS required, works in IE9 and up:
<svg viewBox="0 0 1 1" width="100" height="100">
  <image xlink:href="path/to/image.jpg" 
    width="100%" height="100%" 
    preserveAspectRatio="xMidYMid slice"/>
</svg>
Code language: HTML, XML (xml)
Let’s break down how this works:
- The last two values in the 
viewBoxattribute define our desired aspect ratio, in this case a square (1:1). - The first 
widthandheightand attributes tell the browser the default dimensions of our cropped image. We can make these any number divisible by our ratio, and we can override them in CSS just like<img>elements. - The 
<image>element’sxlink:hrefattribute points to the source image (just like<img src="…">). It can be any size or aspect ratio. - The second 
widthandheightattributes force the image to fill the entire<svg>. Alternatively, you can use the same values as the ratio defined in theviewBox. - Finally, the 
preserveAspectRatioattribute’sxMidYMid slicevalue tells the browser to center the image, slicing off any overflow. You can experiment with different alignment values depending on the needs of your design. 
Here it is in action:
This technique isn’t perfect. Adding alt text is a tad more complicated, and SVG’s <image> element does not support srcset or sizes. But it should tide us over till object-fit is better supported, at least when server-side cropping isn’t an option.

Tyler Sticka has over 20 years of experience designing interfaces for the web and beyond. He co-owns Cloud Four, where he provides multidisciplinary creative direction for a variety of organizations. He’s also an artist, writer, speaker and developer. You can follow Tyler on his personal site, Mastodon or Bluesky.
