CSS: animating a navigation menu

The concept of CSS transition applies only to particular states of an element. A CSS transition is much like an event listener: it keeps track of the properties of an element and when such properties change during a state, it simply applies an effect to the affected properties. States, for example, are :hover and :focus. Transitions work this way: you have to register a transition on the normal state of an element and then change some properties on a different state of the element (e.g. :hover). In this post I'll show you how to animate a navigation menu using transitions.

We have a simple navigation menu:

<ul id="navigation">
	<li><a href="#">Home</a></li>
	<li><a href="#">Articles</a></li>
	<li><a href="#">About</a></li>
</ul>

with some simple CSS rules:

body {
	margin: 0;
	padding: 0;
	font: 100% Arial, sans-serif;
}

#navigation {
	height: 3em;
	margin: 0;
	padding: 0 1em;
	list-style: none;
	background: #000;
	border-top: 0.6em solid #d34545;
}

#navigation > li {
	float: left;
	height: 100%;
	margin-right: 1em;
	font-family: 'Arial Black', Arial, sans-serif;
	position: relative;
}

Now we apply a rule on all links and we register a transition on them:

#navigation > li > a {
	float: left;
	height: 100%;
	line-height: 3;
	padding: 0 1em;
	text-transform: uppercase;
	letter-spacing: 0.1em;
	text-decoration: none;
	color: #ddd;
	-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;
	width: 7em;
	text-align: center;
}

We want to animate the background, text color and width of such links. Here's how we can do:

#navigation > li > a:hover {
	background: #d34545;
	width: 8em;
	color: #fff;
}	

All the properties specified in the last rule will be affected by the previously registered transition. If you want to learn more on it, check out this tutorial. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.