Fixing gaps between WP navigation menu items

Recently I was working on a child theme of Storefront, which by default changes the colour of whichever menu item you’re hovering over. If you hover over the example menu below you’ll see what I mean.

  • Home
  • Blog
  • Contact

Works fine, right? Then I decided I’d like the selected menu to show in a different colour to help users know where they are. So for example if you’re on the home page, the menu would look like this:

  • Home
  • Blog
  • Contact

But now when you hover over the menu items, there’s a problem. Move the cursor between Home and Blog and a small gap between the menu items is glaringly obvious. The same gap is between all the items actually, but it’s not noticeable in the first example.

What’s causing it? The Storefront design styles all the menu <li> elements as inline-block, and that means any whitespace will appear as a gap. There’s a full explanation as to why and the various ways you can handle it over on CSS-Tricks, but the simple answer is to get rid of the whitespace.

That particular bit of html is generated by wp_nav_menu so we just need to filter the output and strip out the gaps between a closing </li> tag and the next opening <li> tag. We do that using preg_replace, and the whole snippet that goes in the child theme’s functions.php file looks like this:

function mytheme_remove_menu_whitespace( $items, $args ) {
	if ( 'primary' == $args->theme_location ) {	// Only run the preg_replace on the desired menu
		$items = preg_replace( '/<\/li>\s+<li/', '</li><li', $items );
	}
	return $items;
}
add_filter( 'wp_nav_menu_items', 'mytheme_remove_menu_whitespace', 10, 2 );

Leave a Reply

Your email address will not be published.