The images are not uniform in dimensions. They are like square or rectangle or vertical. I want to be able to display the images in a square and the entire image has to be displayed, not cropped. How can I achieve this?
Youâll need to experiment for yourself with your images to know for sure if the distortion is acceptable.
To me a few pixels either way isnât noticeable. But I donât have an artists eye.
The original image dimensions here are width=â325â height=â112â and the distortion is IMHO unacceptable - I would Crop or Pad instead.
They have to be specified if you want it to display at a different size from the original. In the CSS you can specify them using em or % - they donât need to be defined in px.
If your images are pictures of something (like people or places) then please do not squish or stretch them as that is very amateurish and hated by web users. If the images are just decoration or design patterns then yes you can squish them as no one will know they have been changed.
Think carefully about this and think carefully about the logistics of what you are asking.
In order to maintain the correct aspect ratio you need to use âbackground-size:coverâ (assuming background images). This will control the aspect ratio while filling the div but of course there may be portions of the image now outside the viewable area.
Lastly remember that images in the html are considered content and should the images be decoration they should remain as background images.
In the end its just a matter of basic math and you canât fit a square peg in a round hole.
If we could see your images we may be able to say what is the best approach for those types of images.
No disrespect to Craig Buckler but that article is from Nov 2013.
Seems to me it would be easier to use contain / cover depending on whether one wanted to strictly maintain a shape at risk of losing a few pixels (due to overflow hidden) or retain all the image at risk of the shape.
* what I called Pad looks to be more appropriately called âletterboxedâ.
That technique simply does what background-size:cover does for background images and is basically the approach I recommended. (You could have used âobject-fit:coverâ for foreground images instead but IE has no support yet.)
The technique makes sure that an image is always bigger (or as big) than the area that you want it to fit into and then hides the overflow. It does not change the aspect ratio and so the images look ok although some parts will be outside the viewing area.
In which case IE never will because IE11 now only receives technical and security support - so whatever functionallity IE doesnât support will now never be added to IE as no version of IE is still receiving updates to support new functionality.