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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With