I’m writing a JQuery script which evenly spaces variable-sized horizontal navigation links inside a containing <ul>, using margin-right. The algorithm is:
A: Get width of <ul> container.
B: Add up widths of all <li> items inside container.
C: Calculate right margin for each item except the last <li> by subtracting B from A and dividing by the number of <li> items in the container, minus 1.
But there is a flaw either in my algorithm or in my code, because the links are overflowing the container. Here is my code. Can you help please?
Thanks,
-Northk
var containerWidth = $('#main-nav ul').width();
var linksWidth = 0;
$('#main-nav ul').children().each(function() {
linksWidth += $(this).width();
});
var linkSpacing = Math.floor((containerWidth - linksWidth) / ($('#main-nav ul').children().length - 1));
$('#main-nav ul').children().css('margin-right', linkSpacing + "px");
$('#main-nav ul').children().filter(":last").css('margin-right', 0);
And the HTML looks like:
<nav id="main-nav">
<ul>
<li>
<a href="#">home</a>
</li>
<li>
<a href="#">link-number-2</a>
</li>
</ul>
</nav>
I just assumed some css rules but i believe this is what you were looking for.
http://jsfiddle.net/TEDhb/