Fluid Images

A common solution for fluid images is to set the width to 100% and the height to auto. But this approach only considers the width of the viewport and ignores the height: for example an image with the aspect ratio 3:2 viewed in a brower window sized 1200 × 600 pixels is scaled to 1200 × 800 pixels – so 200 pixels are outside of the viewport. Ideally this image should be sized 900 × 600 pixels to fit into the viewport. We can achieve this by sizing the width of the image container with vh units: a maximum width of 900 pixels equals 150vh: 100vh (the full viewport height) × 1.5 (the ratio of the image).

There is one downside to this: viewing this on a larger screens could scale images past their maximum size. But an upper (1200 pixels) and/or lower limit (742 pixels) can be added with (vertical) media queries. Here is a SCSS mixin to achieve this:

@mixin limit-width($min-width, $max-width, $ratio) {
  max-width: $min-width;

  @media screen and (min-height: round($min-width / $ratio)) {
    max-width: 100vh * $ratio;
  }

  @media screen and (min-height: round($max-width / $ratio)) {
    max-width: $max-width;
  }
}

figure {
  @include limit-width(742px, 1200px, 1.5);
}

The compiled CSS:

figure {
  max-width: 742px;
}

@media screen and (min-height: 495px) {
  figure {
    max-width: 150vh;
  }
}

@media screen and (min-height: 800px) {
  figure {
    max-width: 1200px;
  }
}

So the initial maximum width is set to 742 pixels. Between 495 and 800 pixels viewport height the maximum width of the image scales between 742 and 1200 pixels (or stays at 742 pixels if vh is not supported). And for heights larger than 800 pixels the maximum width is fixed at 1200 pixels. See an example below – if you are resizing the browser window the image should always fit into the viewport:

Parking Car
Photo taken from a series about Mount Kōya

For the photography section on this site I’ve changed the aspect ratio from 3:2 to 1:1 as I’ve been shooting more and more on medium format.