Dynamic Padding Horizontal Navigation

This is something that I don't seem to commonly come across, but I think it's a good thing to have in my arsenal nonetheless. This script uses jQuery to dynamically pad horizontal navigation elements to fit a specific width container (great for CMS where you can't build static nav structures).
The theory is simple; the script figures out the width of the total elements, the number of elements, and you supply the width of the container, and jQuery pads the left and right of each element to make each element evenly spaced across the bar. Any remainder from the calculations (typically less than 5px) is added to the last item in the list.
Demo
View a demo of the dynamically padded navigation.
Source Code:
First things first - this obviously requires jQuery 1.2 or above, so get that setup.
The structure of the HTML is pretty standard for anyone who uses unordered lists to create navigation schemes:
<ul class="nav"> <li><a href="#">Item One</a></li> <li><a href="#">Item Two</a></li> <li><a href="#">Item Three...
The CSS uses the following convention, though it can be modified to fit your needs:
.nav { margin: 20px 0; padding: 0; }
.nav li { margin: 0; padding: 0; list-style: none; }
.nav li a { display: block; float: left; margin: 0; padding: 10px 0; background: #e0dddd;
font-weight: bold; color: #404b69; border: 1px solid #ccc; }
.nav li a:hover { background: #fff; color: #000; }
Then the javascript:
function elastoNav(w){
var curwidth = 0;
var totalelements = 0;
$('.nav li a').each(function(){
curwidth = curwidth + $(this).outerWidth();
totalelements = totalelements + 1;
});
if ((w-curwidth)>0){
var pad = Math.floor(((w-curwidth)/totalelements)/2);
$('.nav li a').css('padding-left', pad+'px').css('padding-right', pad+'px');
// Check for remainder
var newwidth = curwidth + (totalelements*(pad*2));
// Add padding to last element to close remainder gap
if(newwidth<w){
var remainder = w-newwidth;
$('.nav li a:last').css('padding-right',(pad+remainder)+'px');
}
}
}
Just call that function using the document.ready (or $(function(){})) method and pass in your width and you're all set.
Obviously this isn't a jQuery plugin or a final solution, but it will hopefully save you the time of coding it all yourself. If you get stuck please check out the source for the demo or leave a comment below.
Responses to this Article:
Loading Comments...
I am a web developer, designer, and consultant located in the La Crosse / Onalaska Wisconsin region with
over twelve years experience developing and managing projects ranging from large applications and cloud-based
business solutions to social/new media campaigns, to complete system and infrastructure implementation.