Thursday, July 8, 2010

Drop Shadows in CSS with jQuery

We were discussing drop shadows around the office today. CSS natively supports it, it turns out – as long as you're running Safari or Opera. For the rest of us, we can get around it with a little trickery.

The method I'm using doesn't require Javascript, but Javascript automates the process, meaning you don't have to duplicate everything by hand.

<script type="text/javascript"><!-- $(function() { $('.shadowed').each(function (index, elem) { $(elem).append('<div class="drop-shadow" style="opacity: 0.25;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=25);position:absolute;top:2px;left:2px;">' + $(elem).text() + '</div>'); $(elem).parent().height($(elem).parent().height() + 4); $(elem).children('.drop-shadow').css('font', $(elem).css('font')); $(elem).children('.drop-shadow').css('color', $(elem).css('color')); $(elem).children('.drop-shadow').width($(elem).width()); $(elem).css('position', 'relative'); }); }); --> </script>

Then, all you have to do is declare an element with the "shadowed" class and let Javascript take care of the rest. The drop shadow will automatically assume the correct position and style.

For simplicity's sake, the CSS for the drop-shadow class is declared in the script. You may want to move it into your CSS file to de-clutter things.

Caveat: If the parent element to your shadowed element is subject to resizing, you will need to update the drop-shadow element's width when the parent width changes. Also, you will want the parent element to have some padding to keep the drop shadow from overrunning it.

Here's an example of the drop shadow in action. (If you view the source, you'll notice that I hard-coded the CSS for this example.)
Here's an example of the drop shadow in action.

No comments:

Post a Comment