Follow Brian Li (@DecryptoBL) on Twitter.
Follow Brian Li (@bwhli) on Instagram.

How to Remove Whitespace in a WordPress Navigation Menu

December 11, 2018

Earlier today, I saw some strange and unintended text movement in my header and footer menus. The menu items on uncached pages had less whitespace between them. Here’s what my header menu looked like on uncached pages.

Here’s the same header on cached pages.

The difference is very subtle, so here’s a GIF that makes it a little more obvious.

After some troubleshooting, I discovered the issue was caused by WP-Rocket’s HTML minification. Specifically, I didn’t specify the 'item_spacing' argument in my navigation menu functions. In order to fix the issue, all I had to do was add 'item_spacing' => 'discard' to my navigation menu function array. According to the WordPress codex, 'item_spacing' specifies “whether to preserve whitespace within the menu’s HTML.” Here’s the full code for my header nav menu that discards whitespace to normalize menu appearance between uncached and cached pages.

<?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'container_class' => 'header-menu', 'item_spacing' => 'discard' ) ); ?>

Questions?

Find me on Twitter, or send me an email.