XML technologies / CSS / CSS Cookbook / Images / Adding shadows to images
(Excerpt from “CSS Kochbuch” by Christopher Schmitt)
Problem
Display a shadow behind an image, as shown in the following figure.
Figure: An image with a shadow.
Solution
Wrap the image (see the next figure) in an element div. Give it an attribute class whose value in our example is imgholder:
<div class="imgholder">
<img src="dadsaranick2.jpg" alt="Foto von Papa, Sara und Nick" />
</div>Figure: The image placed above the content.
The div is defined as a left-aligned float, allowing text to flow around it on the right. Next, insert the shadow as a background image. For reasons explained in the discussion, we use two declarations of background, the first using an image format supporting transparent alpha channels, such as PNG:
div.imgholder {
float:left;
background: url(dropshadow.png) no-repeat bottom
right !important;
background: url(dropshadow.gif) no-repeat bottom right;
margin: 10px 7px 0 10px !important;
margin: 10px 0 0 5px;
}With the properties margin-right and margin-bottom, we can specify the shadow’s width. To enhance the effect, also give the image a border and margins:
div.imgholder img {
display: block;
position: relative;
background-color: #fff;
border: 1px solid #666;
margin: -3px 5px 5px -3px;
padding: 2px;
}Discussion
First create an image containing the shadow in an image editor such as Adobe Photoshop. The background image should measure at least 600 x 600 pixels (see the next figure), making it usable for almost any web image.
In the first CSS rule for the background image, we use a rule !important to give the PNG file precedence over the GIF file defined later. PNG lets the document’s background color change without adjusting the shadow. Older browsers, such as Internet Explorer for Windows before version 7, which do not follow this rule correctly, instead use the second rule with the GIF background image to display the shadow.
The properties margin-left and margin-bottom let us specify the width of the shadow below the image and its distance from the image’s edge. If the shadow’s width on the right or left exceeds 5 pixels, as in our solution, adjust the value accordingly.
Figure: The shadow is visible on the right and bottom.
See also
The article on using shadows on the A List Apart website, and the recipe Adding soft drop shadows to images.
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