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.
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.
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;
}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.
Copyright of the German edition © 2007 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “CSS Kochbuch” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln