Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to fit an image into a box without distortion

Short answer

Give the image the needed size and object-fit: cover — it fills the whole box, and the excess is cropped:

<img src="/media/photo-800x500.jpg" alt="A flower" style="width: 200px; height: 200px; object-fit: cover;">

cover or contain

cover fills the whole box and crops the edges. contain shows the whole image, leaving empty bars on the sides or at the top and bottom:

<style>
  img { width: 160px; height: 160px; background: whitesmoke; border: 1px solid silver; }
</style>
 
<img src="/media/photo-800x500.jpg" alt="cover" style="object-fit: cover;">
<img src="/media/photo-800x500.jpg" alt="contain" style="object-fit: contain;">

cover suits previews and covers, contain — logos and products where everything must be visible.

Equal cards

In a grid of cards, images of different proportions are evened out with one height or a shared aspect-ratio:

<style>
  .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
  .grid img { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 6px; }
</style>
 
<div class="grid">
  <img src="/media/photo-200x200.jpg" alt="Square">
  <img src="/media/photo-600x200.jpg" alt="Wide">
  <img src="/media/photo-400x250.jpg" alt="Medium">
</div>

Common mistake

The image gets both width and height without object-fit. The default value fill applies: the image stretches to the box and gets distorted:

<img src="/media/photo-600x200.jpg" alt="A stretched banner" style="width: 200px; height: 200px;">

Functions used in this recipe

  • object-fit — How the picture of an `<img>` or `<video>` fits into the element's box.
  • <img> — An image.
  • aspect-ratio — The ratio of width to height: the browser computes the missing dimension.
  • object-position — Which part of a cropped `<img>` or `<video>` stays visible.

Thanks for reading!

Donate to the site — we work hard for you.