jQuery Full Width Navigation Plug-in
Published Friday, November 09, 2007 in Javascript, jQuery, Progressive Enhancement
In the (not so distant, hopefully) future, creating full width navigations will be a piece of cake using display: table, table-row and table-cell, but until certain browsers get up to speed with CSS here's a plug-in you can use to make any navigation created with the HTML-elements ul li and a full width.
It assumes a few things about your navigation's styling. The li's mustn't have any padding-right/left or margin-left, but may have some margin-right (to separate the menu-items (or pull them together using negative margin, it supports that too). The a's mustn't have any margin-left/right but the plugin supports different padding left than right and will take that in to the calculation of the new width, obviously the a's should be displayed as block as well.
It may seem lazy not to support any combination of margin or padding in any element, but the fact is it was a bit of a hassle to get everything working as it is and every navigation I've ever created sets all padding in the a and only margin-right in the li and I can't imagine a navigation you can't create in the same way.
The way it works is that it measures the inner-width of the ul (the "navigation-container") and then the total outer-width of all the li's (including their margin-right). Then it calculates how much each nav-item needs to increase in width in order for the li's to take up as much space as the ul's inner-width. Because fractional pixels aren't exactly supported anywhere the plug-in may give different paddin-left from padding-right, and the last li will take care of whatever's left over. The last li will also have its margin-right set to 0.
As usual usage is quite simple, just go: $('#navigation ul').fullWidthNav(); and that should do the trick.
It requires jQuery and the dimensions plugin for jQuery and you can get the code here.
Have fun and let me know what you think.







Comments
4 comments so far, why don't you post one too?
Friday, November 09, 2007 | View all comments by Si Jobling
You just had to go and beat me to it, didn't you? Serves me right for being sick and slow this week.
Sunday, November 11, 2007 | View all comments by Andreas
Hehe, sorry bout that mate, didn't mean to nick it from you.
Your's wasn't jQuery tho was it?
Also, when are you gonna start feelin better? Got bad pool-cravings geez!
Tuesday, February 17, 2009 | View all comments by David Hart
Thanks for this. Just a quick note: in order to get this to work, I had to change line 39 to
tabWidth -= parseInt(jQuery('li:last-child', ul).css('marginRight'),10);Tuesday, February 17, 2009 | View all comments by Andreas
@David Hart - Ah nice catch. There may be more of them, especially cross-browser. This is a plug-in I've discontinued though. You can achieve the same effect much easier with display: table/table-row/table-cell.