Demo: Resizing Background Image Demo
Problem:
I’ve been given a project to make a background image resize with the browser window size while retaining its ratio, not causing scrollbars, and always filling up the whole window. It seems pretty easy until you actually see it. Here’s a real life example of it: http://ringvemedia.com/. As you can see it pans as the browser is resized larger until a certain point and then it expands. It never breaks its width to height ratio.
Solution:
The solution is quite simple. It only involves using some CSS and a table.
First we need to make sure the image doesn’t overflow and cause scrollbars.
html,body,#bg,#bg table,#bg td { width:100%; height:100%; overflow:hidden }
Then we need to center the div and make sure it’s not too small.
#bg { position:absolute; width:200%; height:200%; top:-50%; left:-50%; }
Finally, center the image. I’m not exactly sure why a table is needed in the html, but it does work better in filling the window with it in.
#bg td { vertical-align:middle; text-align:center; } #bg img { min-height:50%; min-width:50%; margin:0 auto; }
This is some pretty unique css coding and I’ve seen it in a couple places. Surprisingly (not), it’s the same code at both sites! I wonder who copied who? Well, I can’t say I didn’t do that either.