CSS Crop image and set bounding box accordingly

Viewed 51

I am trying to crop images in CSS but can't get it work as I wish. Here are three pictures to understand my problem :

The following screenshot represent what the "uncropped" elements look like.

uncropped image

For exemple, let's say I only want to keep the part of the first image going from 20% of its height to 60% of its height.

I tried to apply the following CSS to my red rectangle :

clip-path: polygon(0% 20%, 100% 20%, 100% 60%, 0% 60%); 

And the result is

badly cropped image

Which is not good because there is still some blank space around the first image (the gray background was added for better visualization.)

The result I am trying to achieve is this

nicely cropped image

I got that by hardcoding values but this won't be possible.

Is this achievable with CSS only, and knowing the width and height of the original image ?

1 Answers

Solution 1:

using object-fit, object-position :

.col {
  margin: 50px auto;
  width: 300px;
}

img {
  width: 100%;
  display: block;
  object-fit: cover;
}
<div class="col">
  <img style="object-position: 0 80%; height: 100px" src="https://source.unsplash.com/qap1hMjDA-g" />
  <img src="https://source.unsplash.com/22CdQfKG8uM" />
</div>


Solution 2:

using background-size, background-position :

.col {
  margin: 50px auto;
  width: 300px;
}

.img1 {
  background: url("https://source.unsplash.com/qap1hMjDA-g");
  background-size: cover;
  background-position: 0 70%;
  height: 100px;
}

.img2 {
  background: url("https://source.unsplash.com/22CdQfKG8uM");
  background-size: cover;
  height: 300px;
}
<div class="col">
  <div class="img1"></div>
  <div class="img2"></div>
</div>

Note that you need to know the height of the images if you're using second solution

Related