Equal sized navigation menu with jQuery in WordPress

A couple of recent WordPress websites we built called for having the menu items equally spaced out across the whole width of the containing div.

Working in percentages it’s pretty easy to work of course. Our containing div is 100%, so just a count of our menu items, in this case 5, 100/5 = 20, so each menu item is 20%. So the CSS would look like this;

#navigation ul {
	width: 100%;
}
#navigation ul li {
	width: 20%;
}

Of course this works fine when we know the exact number of menu items – and it’s not going to change. But in the real world people use CMS’s, and joyfully add as many menu items as they wish – which means our little bit of CSS will break.

jQuery Self-resizing Menu.

So here’s our quick solution using just a few lines of jQuery, the code below is wrapped for WordPress, but if you’re not using WordPress (why not!) you can drop the jQuery(function($){ wrapper.

jQuery(function($){
	$(window).load(function() {
		// count the number of li items in the main navigation
		var howmanyitems = 0;
		if ( $('#navigation   ul:first-child > li').length > 1 ) {
			howmanyitems = $('#navigation  ul:first-child > li').length;
			//divide by 100 to get the li width
			var menuwidth = 100/howmanyitems;
			// and alter the css to suit
			$('#navigation ul:first-child > li').css( "width", menuwidth+"%" )
		}
	}); // END window ready
}); // END function

This should be pretty explanatory, first set the number of menu items to zero, next we use the length method to see if the number of menu item (li) is greater than 1. If it is then we set a variable (howmanyitems) to this figure, then do the division. Now we have our percentage its just a case of adding our css into the page.

REMEMBER

Adjust the id’s or classes to suit your theme and CSS styling.

Pitfalls

This method equally sizes the menu items – but doesn’t take into account the actual labels you’re using. So if you have vastly different length labels on your navigation you may need some extra effort.

Published on in Coding.

Author Bio

Gary

Other posts by , my email address gary@gdswebdesign.co.uk, on the web https://gdswebdesign.co.uk.

Creating website designs at realistic prices & delivering results.