Hi there! I'm Brandon Cash. I enjoy blogging about new Web technologies and other Web-related things.

CSS Tip: Icon Drop Shadows

CSS Icon Drop Shadows

This neat little trick utilizes CSS3 masks to add a drop shadow to any icon or image with alpha transparency. We’ll be using the pseudo-element :before to create a duplicate of the icon on top of its shadow. Now, let’s jump into the thick of it!

Grab any icon you like. For this example, I’m using an error icon from the wonderful Silk icon set, but you can use anything with alpha transparency. Anywhere you’d like the icon to pop up, place some markup like so: <div class=”error”><img src=”error.png” alt=”Error” /></div>. While the img isn’t really necessary for this trick, it will be more graceful should the CSS fail to load. That being said, let’s go ahead and tell that image to not be displayed in the CSS: div.error img { display: none; }

Now we can create the drop shadow. We’ll use div.error for that. First off, make it an inline-block element so it can sit next to other elements. Give it the width of your icon in pixels. Since we need an extra pixel of space at the bottom for the shadow, give it the height of your icon plus 1px. The icon I am using is 16px by 16px, so I will need to make this element 16px by 17px. Set a background color for the shadow; if you want transparency, use rgba(). Finally, we need to set the mask image. For WebKit, this is done with -webkit-mask-box-image. Here’s what you should have so far:

div.error {
    display: inline-block;
    width: 16px;
    height: 17px;
    background-color: rgba(0, 0, 0, 0.5);
    -webkit-mask-box-image: url(error.png);
}

If you load this up right now, you’ll see that you have a 50% translucent black shadow in the shape of your icon. Now it’s time to add the actual icon image on top of it. For this, we need to use div.error:before. Once again, make it an inline-block element. Since this one doesn’t need any extra room, assign it the width and height of your icon. Give it some content (an empty pair of quotes works just fine), and then set the background image to that of your icon. Let’s take a look at the CSS for that:

div.error:before {
    display: inline-block;
    width: 16px;
    height: 16px;
    content: “”;
    background-image: url(error.png);
}

Reload, and you should find your icon with a lovely little shadow. Play around with this effect and see what you can achieve!

Posted 4 months ago css tip

About Me

I am a freelance Web developer and designer from Springfield, Missouri. Sometimes I like to do crazy Web experiments.

Twitter

What's this madness? You've reached the end of the page!
Next post. → ← Previous post.