Creating background colour transitions on hover
Take a look at the demo of what we’ll be achieving here.
To instruct the browser to use transitions, the following CSS code needs to be used on the selector which is for the menu item itself:
-webkit-transition: all 300ms ease 0s;
-moz-transition: all 300ms ease 0s;
-ms-transition: all 300ms ease 0s;
-o-transition: all 300ms ease 0s;
transition: all 300ms ease 0s;
And quite simply, when the user hovers over the element, the CSS code is:
For the transition code, the properties above are theÂ shorthand version (like the “background” property is the shorthand version of all the different background-* properties). An explanation of what “all 300ms ease 0s” means:
- all: this specifies what property the transition should apply to; in this case I could replace “all” with “background”
- 300ms: the transition will last for 300 milliseconds from start to end
- ease: this allows you to manipulate what happens during the transition – for example, replacing “ease” with “ease-out” would make the transition slow near the end
- 0s: this is the delay in seconds before the transition starts – as you might guess, 0s means the transition will start immediately on hover
CSS transitions work in Firefox 4 and above, Chrome 4 and above, Safari 3.1 and above and Opera 10.5 and above. Unfortunately, only Internet Explorer 10 and above support CSS transitions, so users on version 9 (which still has a large usage share worldwide) won’t get the same experience.
Firefox 4 to 15, Chrome 4 to 25, Safari 3.1 to 6.0 and Opera 10.5 to 12.0 only support transitions using their vendor-specific property. Until usage of older versions of these browsers become irrelevant, you will need to also use them. Using them is technically invalid CSS code, but if you want a pure CSS solution and wide browser support, there’s very little choice.
Have fun coding!