XML technologies / CSS / CSS Cookbook / Images / Scalable images

(Excerpt from “CSS Kochbuch” by Christopher Schmitt)

Problem

Images should scale when the browser window changes size.

Solution

Specify image widths as percentages (see the following two figures):

img {
 border: 1px solid #cecece;
 width: 60%;
 float: left;
 margin-right: .7em;
 margin-bottom: .5em;
}

Modern browsers scale image heights in proportion to their widths, so specifying both width and height is unnecessary.

The scaled image

Figure: The scaled image.

Discussion

In liquid or flexible layouts, text block widths and heights adapt dynamically to the browser window. Images whose dimensions are specified in pixels, however, retain their size.

To keep all page elements in proportion in flexible layouts, developers can also specify image heights and widths as percentages.

The image grows with the browser window

Figure: The image grows with the browser window.

With this approach, scaling can make images appear incorrectly. JPEG artifacts or individual GIF pixels may become visible.

To prevent this, use the property max-width to define a maximum image width (see the next figure):

img {
 border: 1px solid #cecece;
 width: 60%;
 max-width: 300px;
 float: left;
 margin-right: .7em;
 margin-bottom: .5em;
}

The image scales only up to max-width

Figure: The image scales only up to the value of max-width.

See also

The recipe Flexible multicolumn layouts with floats and the recipe Flexible-width multicolumn layouts using positioning.

  

 

 

 

back to top