I am loading images in multiple places where the site theme will have them displayed in different sizes. I experimented with the CSS properties and found that I could scale the image using the height and width parameters and crop the image using position:relative and overflow:hidden.
What I want to do though is a combination of that. To scale the image down until the width is the width of the container element or the height is the height of the container element (which ever comes first). Then crop the rest.
Thus the image should be in proportion and also fill the container, regardless of shape.
Any ideas?
Marvellous
You can use javascript and css. Javascript to check the image heights/widths, then apply appropriate css.
Javascript (note: using zeptojs which is pretty similar to jQuery):
CSS:
To reword your question more succinctly; you want to scale an image to fill it's container element. This can't be done at the moment only using CSS3, but Christian Varga has achieved it beautifully using jQuery:
https://christianvarga.com/jquery-resize-image-to-parent-container-plugin/
I'm not entirely certain what you're trying to do, but here is some guidance that will help you use only CSS properties to achieve some image resizing and clipping.
The code below will resize an image to whatever the container is.
the key is understanding that height and width properties of the img can use %. Using % in your design is great for giving flexibility. This will of course, force the image to whatever size the parent container is. So if the parent container is not the right aspect ratio it will deform the image.
To preserve aspect ratio you will need to know the dimension to expand along in advance and only specify that in the img tag style. For instance, the below will properly resize the image along the width only.
Using the above, if YOUR_PIC.jpg is 200x200 pixels, it will scale it down to 100px and clip 100px off of the bottom.
If you want it to expand within ranges along with the width/height you would use 'max-width'/'min-width'and 'max-height'/'min-height' css properties on the img. Set those equal to what you need. Then you will have something like this:
The above will make sure that the image doesn't expand for containers larger than 50px but will shrink for any container below 50px.
Alternatively, you can use some javascript to do some calculation of sizes dynamically. This would be useful if you do not know in advance which dimension you want to resize upon. Use javascript to calc the size and then set the above css properties accordingly. I would suggest using jquery to make your javascript life easier.
Hope this gets you on the right track.