Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop an image instead of stretching it

Tags:

css

image

When I insert an image in a container with fixed width and height, the image stretches to fit that space. Is there a way to display the image at its normal size, but with the excess clipped out?

like image 913
amit Avatar asked Apr 12 '10 16:04

amit


People also ask

How do you make a picture fit without stretching it?

Choose Edit > Content-Aware Scale. Use the bottom transformation handle to click-and-drag it to the top. Then, click on the checkmark found on the Options panel to commit to the changes. Then, press Ctrl D (Windows) or Command D (macOS) to deselect, and now, you have a piece that perfectly fits within the space.

How do I stop images from stretching in CSS?

Fortunately, the solution is simple. You just need to replace your image/flex item's align-self property's default stretch value with another value. Instead of stretch you can use center , which will remove the image stretching, and vertically align your image in the middle of its parent container.

Can you crop an image in CSS?

Using object-fit The object-fit CSS property can be used to easily crop images. It can have five values, but cover is the most suitable. By setting object-fit: cover; , the aspect ratio of the image is preserved while still fitting into the size of its content box.


2 Answers

The modern way is to use object-fit: none; (or the more common object-fit: cover; if you want to scale, but without stretching).

img {
    object-fit: cover;
}

93% of browser sessions support this as of 2018 March. — Can I use?

like image 187
Zaz Avatar answered Oct 15 '22 11:10

Zaz


<div style="width: 100px; height: 100px; background-image: url(your image); background-repeat: no-repeat;"></div>

Then in the above DIV you can play with CSS

  • width/height
  • background-position

to create different crop effects.

like image 21
Marco Demaio Avatar answered Oct 15 '22 11:10

Marco Demaio