converting photoshop drop shadow into CSS3 box shadow

This CSS class is for various web browser collected in one rule without transparency (known support: Firefox 3.5+, Chrome 5+, Safari 5+, Opera 10.6+, IE 9+):

.shadow {
    -moz-box-shadow: 4px 4px 4px #000;
    -webkit-box-shadow: 4px 4px 4px #000;
    box-shadow: 4px 4px 4px #000;
    /* For IE 8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
    /* For IE 5.5 - 7 */
    filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
}

...and this CSS class is with transparency support:

.shadow {
  -webkit-box-shadow:4px 4px 0px rgba(0, 0, 0, 0.25);
  -moz-box-shadow:4px 4px 0px rgba(0, 0, 0, 0.25);
  box-shadow:4px 4px 0px rgba(0, 0, 0, 0.25);
  -webkit-transform:rotate(135deg);
  -moz-transform:rotate(135deg);
  -o-transform:rotate(135deg);
  transform:rotate(135deg);

}

I wrote an article covering the conversion of Photoshop Drop Shadow properties into a CSS3 box-shadow. If you are using Sass/Compass you can use the photoshop-drop-shadow compass plugin. If you want to do the math yourself, it's not terribly difficult, below is a simple example written in JavaScript. The two tricky parts are converting the angle into X and Y offsets and converting the spread percentage into a spread-radius.

// Assume we have the following values in Photoshop
// Blend Mode: Normal (no other blend mode is supported in CSS)
// Color: 0,0,0
// Opacity: 25%
// Angle: 135deg
// Distance: 4px
// Spread: 0%
// Size: 4px

// Here's some JavaScript that would do the math
function photoshopDropShadow2CSSBoxShadow(color, opacity, angle, distance, spread, size) {
  // convert the angle to radians
  angle = (180 - angle) * Math.PI / 180;

  // the color is just an rgba() color with the opacity.
  // for simplicity this function expects color to be an rgb string
  // in CSS, opacity is a decimal between 0 and 1 instead of a percentage
  color = "rgba(" + color + "," + opacity/100 + ")";

  // other calculations
  var offsetX = Math.round(Math.cos(angle) * distance) + "px",
      offsetY = Math.round(Math.sin(angle) * distance) + "px",
      spreadRadius = (size * spread / 100) + "px",
      blurRadius = (size - parseInt(spreadRadius, 10)) + "px";
  return offsetX + " " + offsetY + " " + blurRadius + " " + spreadRadius + " " + color;
}

// let's try it
// for simplicity drop all of the units
photoshopDropShadow2CSSBoxShadow("0,0,0", 25, 135, 4, 0, 4);
// -> 3px 3px 4px 0px rgba(0,0,0,0.25)

Tags:

Css

Photoshop