CSS Sliding Underline

CSS Sliding Underline

I’ve seen a few blogs that use a neat effect that is only starting to be utilized around the web – underlines with CSS transitions. We’ve all seen sites that have navigation menus with underlines that fade in and fade out on hover, but what about other animations? What about moving, or sliding, underlines?

CSS Sliding Underline

It is possible, as most things are, with CSS3. It’s not really that complicated either, it just takes a little bit of planning and finesse.

The key is to not think of these as “underlines” but rather a similar CSS property – the good old border-bottom.

Let’s take a look at some examples.

First, let’s go over the typical example that is fairly common across sites and blogs.

Underline – Top to Bottom

Hover over the h3 above. The underline will start with a thickness of 0, and grow to 3px (in this case). You’ll notice that it also manipulates the DOM and moves everything else on the page down 3px. This is because of the style I used, and could be avoided by using position: absolute; or other techniques, but for the sake of brevity I thought I would leave it as is.

Or, you could accomplish this another way (example courtesy of Josh Broton). In this example, we use pseudo-elements and don’t need to account for the border-bottom at all. Another reason this is a great example is because it doesn’t require a set width.

Underline – Top to Bottom

Now how about the example of an underline sliding from the left to the right?

Underline – Left to Right

Go ahead, hover over the h3 above.

This underline will fade in and slide from the left to the right. Clearly we are using CSS transitions here, but how exactly are we accomplishing this effect?

Let’s think about this for a moment. If we want an underline to start from nothing, and grow to a full width, what CSS would be required? Why don’t we set a width of 0, and change it to a pre-determined length on hover?

That works.

The reason this works is because we set white-space: nowrap;. Because the initial width is 0, the h3 would have broken on any empty character. We could have replaced the spaces with   but not all CMS’ would allow a developer or blogger to do that.

So, like in the initial example, we are starting with an underline that is technically there (but not visible) and using CSS transitions to grow it.

Another way of accomplishing this is using pseudo-elements. Thanks again to Josh Broton for taking the time to figure this out! This might even be a better option than my example above, because it allows you to have variable sized elements without having to hard code a width.

Underline – Right to Left

Big thanks to Josh Broton for using his brain and figuring this one out!

Underline – Middle Out

Underline – Slide In, Slide Off

Credit for this example goes to Dion Dirza for pointing out this awesome example!

Underline — Slide In, Slide Off (Inverse)