Thursday, January 14, 2010

Going Nuts with CSS Transitions

How CSS 3 transforms and WebKit transitions can add zing to the way you present images on your site?


Here’s the First markup:
Laying the foundations

You’ll notice we’re using a somewhat presentational class of pull-right here. This means the logic is kept separate from the code that applies the Polaroid effect. The Polaroid class has no positioning, which allows it to be used generically anywhere that the effect is required. The pull classes set a float and add appropriate margins—they can be used for things like blockquotes as well.

.polaroid {
width: 150px;
padding: 10px 10px 20px 10px;
border: 1px solid #BFBFBF;
background-color: white;
-webkit-box-shadow: 2px 2px 3px rgba(135, 139, 144, 0.4);
-moz-box-shadow: 2px 2px 3px rgba(135, 139, 144, 0.4);
box-shadow: 2px 2px 3px rgba(135, 139, 144, 0.4);
}

The actual Polaroid effect itself is simply applied using padding, a border and a background color. We also apply a nice subtle box shadow, using a property that is supported by modern Web Kit browsers and Firefox 3.5+. We include the box-shadow property last to ensure that future browsers that support the eventual CSS3 specified version naively will use that implementation over the legacy browser specific version.

The box-shadow property takes four values: three lengths and a color. The first is the horizontal offset of the shadow—positive values place the shadow on the right, while negative values place it to the left. The second is the vertical offset, positive meaning below. If both of these are set to 0, the shadow is positioned equally on all four sides. The last length value sets the blur radius—the larger the number, the blurrier the shadow (therefore the darker you need to make the color to have an effect).The color value can be given in any format recognized by CSS.

For Rotations Purposes:

For browsers that understand it (currently our old favorites Web Kit and FF3.5+) we can add some visual flair by rotating the image, using the transform CSS 3 property.

-webkit-transform: rotate(9deg);
-moz-transform: rotate(9deg);
transform: rotate(9deg);


Rotations can be specified in degrees, radians (rads) or grads). Web Kit also supports turns unfortunately Firefox doesn’t just yet.

For our example, we want any polaroid images on the left hand side to be rotated in the opposite direction, using a negative degree value:

.pull-left.polaroid {
-webkit-transform: rotate(-9deg);
-moz-transform: rotate(-9deg);
transform: rotate(-9deg);
}

Multiple class selectors don’t work in IE6 but as luck would have it, the transform property doesn’t work in any current IE version either.