Technique C37:Using CSS max-width and height to fit images

Applicability

This technique is applicable to Cascading Style Sheet / HTML technologies.

This technique relates to 1.4.10: Reflow (Advisory).

Description

The objective of this technique is to be able to present images without introducing a horizontal scroll bar at a width equivalent to 320 CSS pixels, or a vertical scroll bar at a height equivalent to 256 CSS pixels for content intended to scroll horizontally. This is done by using CSS max-width and height property techniques that adapt to the available space and keep the original dimensions of the image.

Responsive layouts can add or remove columns or layout blocks, and each part of the layout can be wider or smaller at different points. This technique ensures images do not break out of their layout area, including in one-column layouts where it would cause scrolling.

The basic principles of fitting images are to:

  1. Define the max-width property for images, and;
  2. Define the height property for images, so they enlarge or shrink in the available space and respond to zoom levels.

All images require design finesse by making sure the original size fits the biggest size of the available spaces to achieve good-looking results at a wide range of viewport sizes and zoom levels.

Examples

Example 1: Fitting images in HTML and CSS

The following simple example uses HTML and CSS to create a fitting image. The layout regions adjust their size as the viewport is adjusted. The images subsequently adjust their size to fit within the layout region containers.

The zoom level can be increased to 400% without requiring scrolling in more than one direction. This particular example uses a percent size for the max-width and auto size for the height of the image to remain the original dimensions.



<style>

/* Fitting Images Styling */

.img-responsive {
  max-width: 100%;
}

</style>

<div class="panel">
  <img class="img-responsive" src="..." alt="">
  ...
</div>

Working example: Using Fitting Images for Reflow

Tests

Procedure

  1. Display the web page in a user agent capable of 400% zoom and set the viewport dimensions (in CSS pixels) to 1280 wide and 1024 high.
  2. Zoom in by 400%.
  3. For content read horizontally, check that all images fit in their available space without horizontal scrolling.
  4. For content read vertically, check that all images fit in their available space without vertical scrolling.

If the browser is not capable of zooming to 400%, you can reduce the width of the browser proportionally. For example, at 300% zoom the viewport should be sized to 960px wide.

Expected Results

#3 and #4 are true.