Make an image fill a div entirely without blanks, keep its ratio and be responsive

I thought this would be simple but I was wrong ! There is no CSS to do this easily, you’ll need some JS to make it work properly.

First, we have a div with several img inside. In fact, it’s a slider.

This slider is a background slider, it takes all the browser window space. And we you resize your browser, the images need to be sized so they keep their ratio, but they fill the entire background without leaving any space. Of course, that means the image will be cropped.

Then, I found this blog with a nice function to do the maths.

http://selbie.wordpress.com/2011/01/23/scale-crop-and-center-an-image-with-correct-aspect-ratio-in-html-and-javascript/

The trickiest part is that you need to resize the image depending on the div size and each time you have to verify if you need to set the width or the height.

Published by

Louwii

Web developer, geek, car enthusiast, photographer, DIYer, video gamer... I like many things, maybe too many?

Leave a Reply

Your email address will not be published. Required fields are marked *