Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to crop an image

Short answer

Give the image the needed proportions with aspect-ratio and object-fit: cover — the excess is cropped:

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

The file itself does not change: CSS only shows part of it.

Which part to keep

By default the image is cropped around the center. object-position moves the visible area — to an edge or by exact percentages:

<style>
  img { width: 120px; aspect-ratio: 1; object-fit: cover; }
</style>
 
<img src="/media/photo-600x200.jpg" alt="Left" style="object-position: left;">
<img src="/media/photo-600x200.jpg" alt="Center">
<img src="/media/photo-600x200.jpg" alt="Right" style="object-position: right;">

Cropping to a shape

clip-path cuts a circle, a polygon or a rounded rectangle out of the image:

<img src="/media/photo-400x250.jpg" alt="A flower" width="200" style="clip-path: polygon(50% 0, 100% 100%, 0 100%);">

Common mistake

The image is cropped by putting it in a block with overflow: hidden, and the right piece is found with negative margins. Such code breaks when the sizes or the file change. object-fit with object-position does the same without fiddling with numbers.

Functions used in this recipe

  • object-fit — How the picture of an `<img>` or `<video>` fits into the element's box.
  • object-position — Which part of a cropped `<img>` or `<video>` stays visible.
  • aspect-ratio — The ratio of width to height: the browser computes the missing dimension.
  • clip-path — Clips an element to a shape: only the part inside the shape stays visible.
  • overflow — What to do with content that does not fit into the element.

Thanks for reading!

Donate to the site — we work hard for you.