Quick Tip – Resizing Images Based On Browser Window Size


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

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Sam Dunn

Sam is a partner at One Mighty Roar, a creative design and interactive media company from Massachusetts, USA. He can be found online at Vivalasam and Twitter.

 

Discussion

  1. Nicholas Z. Cardot

    July 10th, 2009 at 3:36 PM

    Wow. I didn’t even know that was possible. Thanks for the tut.
    .-= Nicholas Z. Cardot´s last blog ..10 Beautiful Hand-Sketched Fonts =-.

  2. Arun Shivaram

    July 11th, 2009 at 8:28 AM

    Is it possible that we can reduce the dimensions of the original image (big.jpg), rather that loading a new image (small.jpg). just a doubt? :)
    .-= Arun Shivaram´s last blog ..Recover your Gmail password by SMS =-.

  3. Sam Dunn

    July 11th, 2009 at 11:42 AM

    @Arun Shivaram
    Yes, instead of swapping the src of the img you would want to adjust the height and the width.

  4. M.A

    July 11th, 2009 at 7:36 PM

    Thanks for your tut.

    Could this be used to set a background image that resizes depending on the monitor size by a percentage rather than loading different images?

  5. James

    July 12th, 2009 at 4:39 AM

    Why not just give the image a percentage width to make it resize smoothly?
    .-= James´s last blog ..Special scroll events for jQuery =-.

  6. Sam Dunn

    July 12th, 2009 at 3:30 PM

    @James
    I did mention this in the closing thoughts, by doing that the image would become blurry at times and not all browsers render it as clearly.

    @M.A.
    Yes, it would be a matter of changing that attribute in the CSS for the body when the event is triggered

  7. Ash

    July 13th, 2009 at 11:16 AM

    This only works on horizontal, not vertical resizing. Was that the desired outcome?

    Good tutorial otherwise.

  8. Sam Dunn

    July 13th, 2009 at 11:43 AM

    @Ash
    Yessir, as fluid layout normally operate horizontally. This can be easily applied to a vertical layout as well.

  9. M.A

    July 17th, 2009 at 1:35 PM

    Thanks for the reply Sam.

    I hate to be a pest however Im still struggling. I have the background changing between ‘small’ and ‘big’ depending if the browser window is 700px or greater as you have instructed however I have very little experience with JS. What attributes will need to be changed in order for it to use the width percentage rather than two set images. You said it would be in the CSS but i dont see how? Thanks for your time.

  10. Sam Dunn

    July 17th, 2009 at 3:05 PM

    @M.A
    Is your intention to make a fullscreen background that sizes with the browser? I actually wrote a plugin (Supersized) for that –
    http://buildinternet.com/2009/05/supersized-20-full-screen-imagebackground-slideshow-jquery-plugin-w-transitions-and-controls/

  11. M.A

    July 17th, 2009 at 3:32 PM

    YES! Thanks, thats perfect. Thanks for the quick reply too, very much appreciated.

  12. MC

    August 3rd, 2009 at 11:34 PM

    Is it not possible for javascript to detect screen resolution and using javascript variables in the html image size property to change the image dimensions?

    Wouldnt look nice using a bitmap image but if it were a vector it would look the same whether on a 800×600 or 1920×1200.

  13. Eric

    August 24th, 2009 at 6:30 PM

    Very useful tutorial.

  14. Peter

    September 17th, 2009 at 9:52 AM

    Demo not working on Mac OS X 10.5.8 with Safari 4.0.3, Firefox 3.5.3 and Opera 10.
    Clicking the photo on the demo page just opens http://www.nonsensesociety.com/2009/04/10-spectacular-photographs-by-gordon-mcbryde/
    Am I missing something ?

  15. Zach Dunn

    September 17th, 2009 at 10:28 AM

    @Peter

    The image changes when you resize the browser window itself.

  16. Peter

    September 18th, 2009 at 8:54 AM

    Ah ! I misread …
    I thought clicking an image would open and resize that image relevant to the current browser window size using a Lightbox effect.
    Thanks for setting me straight !

  17. Andrew

    October 10th, 2009 at 4:27 PM

    First of all thank you for this awesome tutorial. I am building a horizontal website so instead of contentwidth i want to use contentheight. I don’t know any javascript at all, but i tried modifying var contentwidth = $(‘#content’).height(); . That didn’t work. So is there any way to do it? thanks.

  18. Andrew

    October 10th, 2009 at 5:14 PM

    To help you understand what I’m trying to achieve, here’s exactly what I want: the image to resize when the browser window height is <700. The code below still doesen't work for some strange reason.

    $(document).ready(function() {

    function imageresize() {
    var contentheight = $(‘body’).height();
    if ((contentheight) < '700'){
    $('.fluidimage').attr('src','little.jpg');
    } else {
    $('.fluidimage').attr('src','big.jpg');
    }
    }

    imageresize();

    $(window).bind("resize", function(){
    imageresize();
    });

    });

  19. Daniele

    November 4th, 2009 at 1:53 PM

    Hello, I need help with this page:

    http://www.agrarioalbenga.it/Dovesiamo.html

    I’ve been using the script as explained but I always get the smaller image, no matter what resolution or browser window width I’m using.

    I’ve tested and it turns out the contentwidth variable always has zero stored in it.

    So I get the big image only if I change 700 to 0, which is obviously no use at all. Can somebody check out the source of my webpage and help me? What am I doing wrong?

  20. Alex M.

    November 6th, 2009 at 5:44 PM

    M.A. view this script, it’s probably does what you were looking for http://www.ajaxblender.com/bgstretcher-jquery-stretch-background-plugin.html
    .-= Alex M.´s last blog ..Rounded Corners (Mootools) =-.

  21. B.S.

    November 22nd, 2009 at 11:15 PM

    I’d like to use this to alter the background image but I don’t know much about JS or CSS. I’ve got the general hang of this example but how would I alter

    background-image:url(images/bustle_525_left.gif);

    call to include the fluidimage class reference?

  22. Matthew Westrik

    February 11th, 2010 at 5:51 PM

    Nice tut…

  23. Jared

    February 18th, 2010 at 11:18 AM

    Awesome. I had considered this for a site I work on, but reading the simplicity of this article pushed me over the edge! With such a huge number of mobile users, and netbook users, we really have to design for them from get-go. Thanks!!

  24. TheInfamousGdub

    February 18th, 2010 at 5:25 PM

    This is VERY much something I need. Thanks!

  25. Darius Connors

    February 19th, 2010 at 3:03 AM

    Awesome.

  26. ivo

    February 24th, 2010 at 8:55 AM

    this can be very helpfull in some cases, thx

  27. Sherwood Botsford

    February 25th, 2010 at 10:01 AM

    A better way to handle this:

    CSS

    .pic-right-70% {
    width: 70%;
    float: left;
    }

    HTML

    [image link]

    [Image caption]

    This lets the image resize continuously,

  28. Ej

    February 28th, 2010 at 5:47 PM

    I love this but can you add any kind of content and Nav and still work the same???

  29. Web Dizajn Artist

    April 1st, 2010 at 7:05 AM

    Tutorial is great! Hope I’ll use it sometime soon!
    Keep it writing! :)

  30. Chanel

    May 17th, 2010 at 9:16 AM

    Great piece of code here, love it!
    I have a question though (following up on Arun’s):
    If I want to adjust the size of the image using only width and height parameters, how would I go about that?
    It seems like a good way to save space on a server…

  31. synapsis

    June 3rd, 2010 at 10:22 PM

    Would it be possible to use this same script to swap between entire CSS files depending on the browser width? I’ve tried other techniques that failed to be cross-browser compatible. I’m hoping this one might be. I’d like to have a widescreen version, a 1024×768 version, and a mobile version of the site — easily done through CSS switching.

  32. Chelsea FC True Blue

    June 4th, 2010 at 6:05 AM

    Is it possible to change blog size depending upon different screen resolutions?

  33. John Media @ server hosting

    June 9th, 2010 at 8:33 AM

    Wow that’s really awesome the Image will change size according to the size of your browser. So if you make it small it would shrink, If you’d make it bigger it would eat up the screen, Its great for zooming pictures when your looking at the details of the image.

  34. Mark R

    June 30th, 2010 at 4:26 PM

    Great code, thank you. Anyone have any idea how this could be applied to multiple images on a page?

  35. phil

    August 18th, 2010 at 12:53 PM

    how can i use this behavior so that it resizes on window height rather than width?

    thanks

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!