HTML and CSS Reference
In-Depth Information
This situation comes up all too often in liquid layouts: fixed-width content that overflows its liquid-width
container. Luckily there's an elegant solution to this common problem.
Fluid Images
It's surprisingly easy to make a naturally fixed-width image behave like a liquid-width box. It takes one rule
in a style sheet:
img { max-width: 100%; }
This simple CSS rule declares that all inline images (all instances of the img element) should never
exceed the width of their containing elements. If the image is smaller than its container it will still display at
its natural size, or whatever size it's been given in CSS or in a width attribute. But if the image is larger
than its container, the browser will automatically scale the image down to fit. A max-width value in a style
sheet will override an inline width attribute, but any widths assigned to an image elsewhere in the style
sheet can still take precedence, especially if they're coupled with a more specific selector.
This rule so far only affects the width of the image, not its height. If you include an inline height attribute—
as we have with our product images—that height value will remain in effect even when the width scales,
changing the image's aspect ratio. This can lead to unsightly squishing like you see in Figure 10-15.
Figure 10-15. An image scales to fit the width of its container, but its height is unchanged. The result is a squeezed and
distorted image, much taller than it should be.
There's a simple and elegant solution to the squishing problem as well:
img {
max-width: 100%;
height: auto;
With the addition of a height:auto declaration, whenever the image's width changes to fit its container,
its height will adjust automatically to preserve the file's original aspect ratio, overriding the image's height
attribute, if it has one.
Search WWH ::

Custom Search