Sliding underline in navigation

Vitaliy Kirenkov
2 min readJun 25, 2021

--

Photo by Jeffrey Workman on Unsplash

TL;DR

CodePen with the result.

Introduction

Hi everyone!

Sometimes in accordance with the design idea it is required that you should not only draw a line under the hovered menu item, but that line should also “flow” from one item to another.

Previously to accomplish that I used the Lavalamp plugin.

The majority of examples I met before:

  • used jQuery;
  • worked with fixed sizes;
  • had an extra empty element in DOM.

My solution:

  • contains minimum JavaScript;
  • menu options can have dynamic width and there is no bound to their quantity;
  • a separate “sliding” element is not added in DOM.

HTML

HTML contains standard menu markup:

CSS

All the magic happens here, in the CSS. The problem of “extra” empty DOM element solved by the pseudo-element.

BUT!

You cannot set pseudo-elements styles from JavaScript. One can set custom properties instead. They are block scoped and obey CSS-cascade. In other words, they forward deeper. Thus, if you set properties for the .menu__list they will be available to its pseudo-elements and other descendant blocks.

If markup is skipped, then key underline styles in CSS:

Pseudo-element styles:

It only remains to do the following in script:

  1. to check the width of the menu option that was hovered over;
  2. to check left offset of the menu option along the Х axis;
  3. set the received values to the wrapper (.menu__list).

JavaScript

First of all, we cache menu in the variable:

Then we need to add mouseover listener to the menu and check whether the cursor points to the link or not:

Inside, we get the values and set them to the corresponding property:

Now add another listener, which resets underline width when cursor leaves the menu:

Conclusion

CodePen, where everything is gathered together (with markup).

If you liked this article, subscribe to my Telegram-channel where I publish best practices and share valuable insights on a regular basis.

--

--

Vitaliy Kirenkov
Vitaliy Kirenkov

Written by Vitaliy Kirenkov

Senior Project Manager, PMP®, PMI-ACP®, A-CSM

Responses (2)