Cropping Images in CSS

Paul Bassi
3 min readMay 21, 2018

--

Being fairly new to web-development I wasn’t exactly sure what the best way to crop images in CSS was, so I did what most new developers do and resorted to cropping them in Preview. That’s until one of my instructors at HackerYou taught me this neat little trick called object-fit.

Original Image- What a beauty

Previously when setting a width and height on an image it would contain the image to those dimensions and the image wouldn’t look right due to the altered aspect ratio. I’ve set a height and width of 300px to the image below. Notice how it’s been squished vertically to fit the box.

Width & Height: 300px

Meet object-fit.

Object fit has 5 values that can be used: Contain, Fill, Cover, None(default) and Scale-Down. I’ll be showing you the first three.

object-fit: contain - The content maintains its aspect ratio and fits the content box. No clipping occurs.

object-fit: contain;

object-fit: fill - The content is stretched to entirely fit the content box. Clipping may occur.

object-fit: fill;

object-fit: cover - The content retains its aspect ratio while filling the entire content box. Clipping may occur.

object-fit: cover;

I’m fairly happy with this crop. But what if I wasn’t and wanted to decide which part of the image to show?

Meet object-position.

Object-position takes two values, the first is an x-value(horizontal), the second is a y-value(vertical). These values can be defined in units such as pixels or percentages, they can also be defined using words(center, top, bottom, left, right).

Continuing with the example above, I’ll apply a y-value of 70% to object-position to bump it up a bit.

object-position: 0 70%

I hope that this post can help someone by showing that it is possible to crop in CSS quite easily and that we don’t need to resort to Preview or Photoshop. Thanks for reading!

--

--