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.

Update: now responsive!

Check out the demo to see it in action.

The plugin is as follows (also available on github):

To use it, ensure that the image is positioned relatively or absolutely inside a wrapper element which has the `overflow: hidden` property set (so the image can take up the entire height/width of the wrapper with the cropped portion hidden). Then, 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:

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. If you have any doubts, check the source of the demo to see how it works.

Please feel free to leave any questions, comments, or suggestions in the comments below 🙂

If this post has helped you out, feel free to consider throwing a small donation my way.