CSS: making an horizontal menu animated with transitions

CSS: making an horizontal menu animated with transitions

How to create an animated horizontal navigation menu with CSS transitions.

CSS transitions allow us to make property values change smoothly over a given time span and also to specify an easing algorithm for the transition. This comes particularly handy when we want to create visual appealing navigation menus.

Here's a simple HTML5 menu:


<nav id="menu">
	<strong>Home</strong>
	<a href="#">About</a>
	<a href="#">Contacts</a>
</nav>

We want to use the top and bottom borders of each item whose width values will be changed during the :hover state. To achieve this effect, we need to add an exact amount of vertical padding so that our items will be vertically centered within their container:


#menu {
	display: block;
	height: 5em;
	overflow: hidden;
}

#menu strong {
	float: left;
	border-top: 2em solid;
	padding-top: 1em;
	padding-bottom: 0.5em;
	border-bottom: 0.5em solid;
}

#menu a {
	float: left;
	margin: 0 1em;
	color: #08c;
	text-decoration: none;
	-moz-transition: all 300ms ease-in-out;
	-webkit-transition: all 300ms ease-in-out;
	-o-transition: all 300ms ease-in-out;
	-ms-transition: all 300ms ease-in-out;
	 transition: all 300ms ease-in-out;
	 padding-top: 3em;
	 padding-bottom: 1em;
	 border-top: 0px solid;
	 border-bottom: 0px solid;
}

#menu a:hover {
	padding-top: 1em;
	padding-bottom: 0.5em;
	border-top-width: 2em;
	border-bottom-width: 0.5em;
}	

On :hover the border width value changes on the top and bottom borders. At the same time, also the vertical padding changes to keep our links vertically aligned.

You can see the demo on this page.