Jaime Quiroz

Present & Future

I recently helped someone out over at the css-tricks forum with a css slide nav ( perhaps influenced by this jquery effect? ). I was inspired by the outcome and decided to make my own example and share the technique.

Mostly basic stuff, the star of the show is the ( ~ ) selector and the sliding of the .highlight element achieved with a simple transition.

HTML

Here we have the basic markup, note the placement of the highlight element. In order for our ( ~ ) selector to work we need to place it after all the nav items.

<ul class="nav">
	<li>hello</li>
	<li>world</li>
	<li>;D</li> 	

	<span class="highlight"></span>
</ul>

CSS

Two main things to look at. First, we set position and z-index rules for the layer order. This is important because we will end up with a laggy-unusable effect if the highlight element is sitting on top the nav items.

li {
position: relative;
...
z-index: 1;}

.highlight {
position: absolute;
...
z-index: 0;
}

We use the ( ~ ) selector to move the highlight element when we hover over the nav items. If you are looking to deal with Internet Explorer support on this, you may want to assign an ID to the nav items for targeting. I however am not concerning myself with additional ID’s for the sake of this example. Instead, I’m using the nth-child selector for targeting the nav items and moving the highlight element. ( supported in Internet Explorer 9+ ).

li:nth-child(2):hover ~ .highlight  {left: 33.3333333%;}
li:nth-child(3):hover ~ .highlight  {left: 66.8%;}

At this point we have a functional nav highlight effect going on.

The ( ~ ) selector will work in IE8 and 7, so this is what it will look like in browsers that don’t support Transitions. Functional, but a bit boring.

To top off the effect, we add the Transition to the highlight element:

.highlight {
...
-webkit-transition: all .5s ease; /* safari & chrome */
-moz-transition: all .5s ease; /* firefox */
-o-transition: all .5s ease; /* opera */
transition: all .5s ease; /* one day we will go prefix free? This one always goes at the bottom. */
...
}

Full code available here.

View the Demo.

You can read more about various other useful selectors in this article.