Next post: Using skia on windows

Image that dynamically fills container, keeping aspect ratio

It sounds so simple,
  • Image should be resized down to fit the size of its parent
  • Image shouldn't be stretched larger than its original dimensions
  • Image should still exist in document flow, no position: absolute
  • Aspect ratio must be preserved
but responsive web design strikes again. Achieving this in pure CSS seems to require background-size:cover or viewport units, but I needed browser compatibility, and had to settle with JavaScript. If the user has disabled JavaScript, at least the image will still be visible. The third-party JQuery plugin jquery.imagefit.js sounded similar to what I wanted, but it uses position:absolute, meaning that I'd have also reposition with JavaScript any content below the image.

So, I wrote my own, from scratch.

// doResize, by Ben Fisher
// requires jQuery
var marginH = 100, marginW = 100;
function doResize() {
  var availh = $(window).height();
  var availw = $(window).width();
  availh = Math.max(10, availh - marginH);
  availw = Math.max(10, availw - marginW);
  if (truew > availw || trueh > availh) {
    var factor = Math.min(availw / truew, availh / trueh);
    $('#targetimage').css('width', Math.round(truew * factor));
    $('#targetimage').css('height', Math.round(trueh * factor));
  else {
    $('#targetimage').css('width', truew);
    $('#targetimage').css('height', trueh);

// after the image loads, call doResize, could look like
$('#featuredimage').load(function() { doResize(); });

// register to respond to any subsequent resize events with
// $(window).resize(function(){  doResize();  });

// truew and trueh can either be set in advance, or read once the image loads

I'm using this code to show a gallery for the digital art I've been working on.