Quick Tip – Resizing Images Based On Browser Window Size
How Is This Useful?
In fluid layouts it is easy to format the text to adjust nicely when the window is resized, but the images are not as fluid-friendly. This Quick Tip shows you how to swap between two image sizes based on the current size of the browser, div, or whatever you decide to make the deciding factor. For those looking for a real life example, Last.fm uses this technique on their artist pages.
The technique that will be used can be expanded to cause additional changes upon resize as well, beyond simply image swapping (ie captions, navigation).
With that said, let’s get rolling.
Step 1 – The HTML You Need
<div id="content"> <img class="fluidimage" src="big.jpg"/> <p>(Type words here)</p> </div>
That’s nice and bite-sized. The main thing to note is that we attached .fluidimage to the image we want to toggle.
Step 2 – Onto the CSS
body{ text-align:center; }
img{ float: right; margin: 0px 10px 10px 10px;}
#content{ width:70%; margin: 0px auto; text-align: left; }
For the sake of simplicity I have excluded any graphical styles such as borders/fonts in the above CSS.
Step 3 – Triggering the Change With jQuery
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script> <script type="text/javascript"> $(document).ready(function() { function imageresize() { var contentwidth = $('#content').width(); if ((contentwidth) < '700'){ $('.fluidimage').attr('src','little.jpg'); } else { $('.fluidimage').attr('src','big.jpg'); } } imageresize();//Triggers when document first loads $(window).bind("resize", function(){//Adjusts image when browser resized imageresize(); }); }); </script>
When the document is ready, we establish a function (imageresize) which swaps the images depending on the width of the browser. If the browser width is less than 700px, the smaller image is used, otherwise the full sized one is displayed. This function is run when the page first loads and anytime the browser window resizes.
Boom, You’re Done
Some of you may wonder why I only have two sizes and didn’t just make the image adjust as a percent of the overall layout. This causes the image to be blurry in some browsers, so I opted to steer clear of that method.
Like I mentioned in the beginning, you could easily add to this technique by display/hiding captions or navigation depending on the browser size. It’s really up to you, but feel free to leave your results and comments below.
The picture used throughout this tutorial was done by the very talented Gordon McBryde



