XML technologies / CSS / CSS Cookbook / Images / Adding soft drop shadows to images

(Excerpt from “CSS Kochbuch” by Christopher Schmitt)

Problem

Give an image a soft drop shadow.

Solution

Soften a drop shadow’s transitions by wrapping the image in a pair of additional nonsemantic tags div.

First create an image in an editor such as Adobe Photoshop, as used here. This becomes a mask to soften the shadow from the recipe Adding shadows to images. Use the same dimensions as the shadow image. Clear all content from the new file, leaving only its transparent background. Then use the gradient tool to create a transition from the background color to transparency (see the following figure).

Choosing the right gradient

Figure: Choosing the right gradient.

Make sure the tool’s background color matches the page background. Now create a 6-pixel-wide gradient from the canvas’s left edge toward the image’s right side.

Repeat these steps, this time creating a gradient from top to bottom.

Save the image as PNG-24 with an alpha channel for transparency (see the following figure).

Saving the image as a PNG with a transparent alpha channel

Figure: Saving the image as a PNG with a transparent alpha channel.

With the image files ready, add the required tags div:

<div class="imgholder">
  <div>
    <img src="dadsaranick2.jpg" alt="Foto von Papa, Sara und Nick" />
  </div>
</div>

First adjust the CSS for the outer element div. The rule float: left floats the image to the left and defines space between it and the remaining content:

div.imgholder {
 float: left;
 background: url(dropshadow.gif) no-repeat bottom right;
 margin: 0 7px 7px 0;
}

Now add the mask, which both softens the shadow’s transition and creates space for displaying the shadow and mask themselves (see the next figure):

div.imgholder div {
 background: url(shadowmask.png) no-repeat;
 padding: 0 6px 6px 0;
}

The shadow’s soft transitions become visible

Figure: The shadow’s soft transitions become visible.

Finally, add padding and a border to the image (see the next figure):

div.imgholder img {
 display: block;
 position: relative;
 background-color: #fff;
 border: 1px solid #666;
 padding: 2px;
}

Further styles for the image with a drop shadow

Figure: Further styles for the image with a drop shadow.

Discussion

The greatest difficulty is creating the PNG with its alpha channel: it must match both the shadow and the page background color.

Internet Explorer for Windows 5.5 and 6 does not support PNGs with transparent alpha channels. The recipe Using multiple PNGs with transparent alpha channels offers a workaround.

  

 

 

 

back to top