Creating menu hover background transitions in CSS

Creating menu hover background transitions in CSS

Improving the user experience of your website visitors is a paramount importance to every Web developer, but many of these user experience improvements is only possible thanks to JavaScript. But not when it comes to creating style transitions – CSS 3 allows you to create them without needing any JavaScript at all. Be aware that CSS 3 transitions are, as of publishing this article, still in draft stages of standardisation and only newer versions of the main Web browsers support them. Some older versions of Firefox, Chrome, Safari and Opera use vendor prefixes (such as -moz-transition) so you will need to use these vendor properties along with the “official” property.

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:

:hover {

background: #fcc852;

}

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

Browser compatibility

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!

Sharing

Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.