
In this example, like in Example #1, the max-width on the image is set to 100% of the container width. This time, however, the image is overlaid with a copy of itself using a CSS background image. This requires a little extra HTML:
<div id="cropped_image" class="image_container">
<img src="basketball.jpg" alt="a basketball game"><span></span></div>
The max-height and max-width of the image container are set to the actual pixel dimensions of the image, so that the container conforms to the size of the image as it grows and shrinks. The span element that immediately follows the image is then absolutely positioned to fill the entire image container, covering the whole image. Finally, the background image and position are set on the span:
.image_container {
position: relative;
}
.image_container img {
max-width: 100%;
}
.image_container span {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
#cropped_image {
max-height: 512px;
max-width: 343px;
}
#cropped_image span {
background: url(basketball.jpg) 50% 50% no-repeat;
}
You may recognize this as the same technique used by Levin Alexander’s Alternate Fahrner Image Replacement. Of course, other image replacement techniques may work just as well, if not better.
When you resize the window, the whole image doesn’t become bigger and smaller. Instead, the image is cropped, keeping the focal point of the image in view and at its original size. Return to the article.