Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing and cropping images with CSS

I have a site that has a bunch of different images to display, all of different resolutions and aspect ratios. Is there an easy way in CSS to resize and crop images to a certain resolution? For my purposes, I want the resized image to be 280x280.

Of course I can just set <img height = '280' width = '280' /> but this will stretch it. I'd like it to the smaller of the two resolutions, make a square, and then take the center pixels. For example, if the resolution is 480x200 I want it to take a 200x200 section out of the center of the image.

I've tried Googling, but to no avail.

like image 279
jas7457 Avatar asked Feb 26 '13 07:02

jas7457


People also ask

Can you resize images in CSS?

The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.

How do I crop instead of resize CSS?

The modern way is to use object-fit: none; (or the more common object-fit: cover; if you want to scale, but without stretching). 97% of browser sessions support this as of 2022 May.

How do I resize an image and keep aspect ratio in CSS?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.


1 Answers

a "real crop" of images with css isn't possible. Real Crop means the the image is reduced to the new values and also it's size is smaller then before.

But there is a solution with negative margins or absolute positioning, which will help you a lot. I've used this technique many times.

Please take a look at: Cropping images with CSS

like image 59
emjay Avatar answered Oct 19 '22 22:10

emjay