Recently I came across a problem whereby I had to dynamically resize an image to fill it’s parent container, exactly like the background-size: cover CSS property but using an image tag instead. The requirements are pretty straightforward – upscale if the image is too small, downscale if it’s too large, and always resize based on the smallest dimension in relation to the aspect ratio of the parent container (which means that you’ll never see any whitespace, the image will always overflow on either height or width). Strangely enough I couldn’t find a jQuery plugin to do quite what I wanted, so I created one.
Check out the demo.
The plugin is as follows (also available on github):
And to use it, simply call resizeToParent on your image, like so (remembering to put it inside the jQuery ready function):
The plugin will automatically resize the image as soon as it’s finished loading. By default, the image will get resized to the nearest parent div. If you want to target a specific parent, simply pass a selector to the function as the ‘parent’ parameter, like so:
Also, don’t forget that the parent container must have ‘overflow: hidden’ so that the image doesn’t spill out of the parent, and the image must be positioned relatively or absolutely for it to be centered correctly.
Please feel free to leave any questions, comments, or suggestions in the comments below