Dynamic resizing while constraining proportions.

Dynamic resizing while constraining proportions.

I really enjoy mobile and touch devices because they effectively present everything in the viewport in a manner that's sized appropriately to the visitor's resolution (with the option to subsequently zoom in/out).

I hate that desktop browsers don't particularly do this natively without a boatload of CSS (% and em declarations), and even then it's difficult to specify appropriate proportions for fixed-ratio elements (e.g. images, video)

I've been working on a fullscreen image gallery that scales appropriately, but I find myself wondering if this could work for any kind of content.

Here's a bit of what I came up with for images this afternoon...

  1. function ResizeWindow() {
  2. var w = $('.image').width();
  3. var h = $('.image').height();
  4. var xw = $(window).width();
  5. var xh = $(window).height();
  6. var s=Math.min(xw/w, xh/h);
  7. var nw = Math.floor(s*w);
  8. var nh = Math.floor(s*h);
  9. $('.image').css('height',nh).css('width',nw);
  10. };
  11. $(window).resize(function() {ResizeWindow();});
  12. $(function() { ResizeWindow(); }

This works fairly well, though Math.floor() will occasionally leave a few pixels at the bottom or right of the viewable area for obvious reasons. What I'm considering however is a plugin that can observe any element you might have in the DOM --fixed width or otherwise-- and scale appropriately. Not only on load, but on resize.



For content, it would probably assume width is always the attribute that governs the logic, so that it results in an iPhone / iPad style behavior of maxing things and allowing vertical scrolling..

Granted, elements like fonts are covered in CSS liquid layouts, but what about thumbnails? I think it'd be nice to detect screen-res first, fetch one of 3 or four thumbnail size options based on that, and then scale those exactly to the designer's taste, while still allowing for the browser's native zoom functionality after the content is initially presented.

Still, I can't help but feeling this is a dumb idea and complete overkill. Maybe there's a CSS aspect I'm totally missing in regards to em?