in ,

LoveLove WINWIN

Crop images with CSS Object-Fit and Object-Position

In this post, I’m going to show you guys how to take any image and crop them to whatever size you want while still keeping the same ratio by using Object-Fit and Object-Position. Let us say we have an image but we wanted to crop it to a specific size by default we can change the image using width and height. Now when we do this we do change the size of the image but it loses its aspect ratio.

<img src="https://vignette.wikia.nocookie.net/dragonballfighterz/images/e/ea/Goku_Artwork.png/revision/latest?cb=20180902173423">
img{
  width: 200px;
  height: 200px;
}

Results

It doesn’t look so good and that’s because an image aspect ratio is important to keep it from losing quality. I’m going to show you guys with this image of Goku how we can crop his face from this image.

Cropping with background-image in CSS

So let’s say you want to crop an image with CSS the old trick was to just use an element then make the image the background and then manipulate the background with height, width, and background-position.

Let create a div with the class of Goku so we can target that element with CSS

<div class="goku"></div>

Now let’s make this div a perfect square and then align the background-position to Goku’s face. Also, take note because we don’t use background-size the image stays with its original size and ratio.

.goku{
  width: 200px;
  height: 200px;
  background-position: -180px -160px;
  background-image: url('https://vignette.wikia.nocookie.net/dragonballfighterz/images/e/ea/Goku_Artwork.png/revision/latest?cb=20180902173423');
}

Results

Cropping with object-fit and object-position

Now we can achieve the same thing that we did by using a background image to crop the face of Goku but this time we will do it with object-fit and object-position.

We create an image tag then add the location of the image in the src.

<img src="https://vignette.wikia.nocookie.net/dragonballfighterz/images/e/ea/Goku_Artwork.png/revision/latest?cb=20180902173423">

Now here is where we do our magic and we set object-fit to none so the image won’t resize when we give it width or height. Then we use the same position like it was a background image.

img{
  width: 200px;
  height: 200px;
  object-fit: none;
  object-position: -180px -160px;
}

Results

Conclusion

Object-fit and object-position are two new CSS properties all of you guys should know about because it can help you manipulate your images much easier than with instead of using the background as an image. If you wish to check what browsers object-fit and object-position are compatible with check this site

What do you think?

Written by CodingPhase

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

0

Comments

0 comments

0

Top 5 Popular CSS Frameworks to Use in 2020

Implement a Queue Using JavaScript