Site logo

Archived topic

Primary Navigation underline for hover/current but with consistent length?

3 replies · Started by Nick on September 2, 2022

Viewing posts 1–4 of 4

Hi,

I really need the underline of the Primary Nav items width to be consistent and match the width of the text above. I've used the below code I've sourced from the Forum but with longer text titles the line is far too short. If I increase the length this then has the opposite effect on shorter page titles.

If possible I'd love this to be animated underline. But if that is too tricky I'd prefer consistency with the underline and not have any animation. Test URL attached in private notes.

Excuse the multiple posts but I thought it best to handle each issue separately to allow the topics to be covered best for others searching the Forum for answers.

Many thanks,
Nick.

Hi there,

first off, we really appreciate you raising a separate topic for each unrelated question, its really helps us focus and as you said makes it easier for other to find :)

Ok, so we need to add this PHP Snippet:

add_filter('wp_nav_menu_objects', 'db_menu_item_featured_image', 10, 2);

function db_menu_item_featured_image($sorted_menu_objects, $args) {

    // Check navigagtion is primary
    if ($args->theme_location != 'primary')
        return $sorted_menu_objects;
    // edit menu items
    foreach ($sorted_menu_objects as $menu_object) {
       $menu_object->title = '<span class="menu-label">' . $menu_object->title . '</span>';
    }

    return $sorted_menu_objects;
}

This wraps the menu item label in its own <span> with the class of menu-label

Now replace your CSS with this:

@media (min-width: 769px) {
    .main-navigation .menu>.menu-item>a>.menu-label {
        position: relative;
    }

    .main-navigation .menu>.menu-item>a>.menu-label::after {
        content: "";
        position: absolute;
        right: 0;
        left: 50%;
        bottom: -5px;
        -webkit-transform: translate3d(-50%, 0, 0);
        transform: translate3d(-50%, 0, 0);
        display: block;
        width: 0;
        height: 2px;
        background-color: currentColor;
        transition: 0.3s width ease;
    }

    .main-navigation .menu>.menu-item.current-menu-item>a>.menu-label::after,
    .main-navigation .menu>.menu-item.current-menu-ancestor>a>.menu-label::after,
    .main-navigation .menu>.menu-item:hover>a>.menu-label::after {
        width: 100%;
    }
}

Hi David,

That's brilliant. It worked a charm, navigation now consistent.

My only suggestion would be a future feature in GeneratePress to include the option to enable this as standard. I say this as I quite often use this type of styling on sites.

Many thanks,
Nick.

Glad to hear thats working

This archived topic is closed to new replies.