Posts Tagged ‘onhover’

How to use CSS3 transitions

If you haven’t used transitions before, here’s a very brief introduction.

On the element you want to have animate, add the following CSS:

#id_of_element {
	-webkit-transition: all 1s ease-in-out;
	-moz-transition: all 1s ease-in-out;
	-o-transition: all 1s ease-in-out;
	-ms-transition: all 1s ease-in-out;
	transition: all 1s ease-in-out;

There is a lot of duplication due to vendor prefixes – until the specification if finalised, this is likely to stay the same. If this bothers you, there are various tools such as CSS Scaffold or SASS that allow you to define mixins to avoid repetitive code.

The syntax is pretty straightforward, you specify the property you want to animate, all or border-radius or color or whatever, the time to run, then the transition timing function. The options for the timing function are shown below.

Whenever any property changes, then it will animate instead of changing directly. This can be due to a different set of properties set on a pseudo class such as hover, or a new class or properties set by javascript. The example below uses :hover to change the properties – no javascript is needed.

In addition to the built in timing functions, you can also specify your own. The excellent Ceaser CSS Easing Tool makes this very easy.

Regarding the properties you can animate, the best way is to experiment. The Mozilla Developer Network maintain a list of properties that can be animated on their CSS Transitions page. These include everything from background-color and box-shadow to column width and box-flex. Many of these properties are not supported by default by jQuery animation, making CSS transitions much more useful out of the box. In addition, iOS hardware accelerates animations that don’t require repaints, namely opacity and transforms.

To find out more, read through the W3C specification.


Cross fading images
One image to another, on hover (transitions)

First up, the HTML markup. Without CSS enabled, you just get two images. Remember to add alt text for production use.

<div id="cf"> <img src="img1.jpg" /> <img src="img2.jpg" /> </div>

Then the CSS:

#cf { position:relative; height:281px; width:450px; margin:0 auto; } #cf img { position:absolute; left:0; -webkit-transition: opacity 1s ease-in-out; -moz-transition: opacity 1s ease-in-out; -o-transition: opacity 1s ease-in-out; -ms-transition: opacity 1s ease-in-out; transition: opacity 1s ease-in-out; } #cf { opacity:0; }