Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Equally Spaced, Variable-Width Navigation Links
ul {
display: table;
width: 100%;
}
li {
display: table-cell;
}
a {
display: block;
}
ul {
display: box;
}
li {
box-flex: 1;
}
(function($) {
$.fn.justifyNav = function() {
return this.each(function() {
var $this = $(this),
$children = $this.children(),
containerWidth = $this.width(),
linksWidth = 0,
count = $children.length;
$children.each(function() {
linksWidth += $(this).outerWidth();
});
// Don't give the last item or the 2nd to last item any right margin, then float the last item right.
// This will account for small errors in JQuery's calculation of the item widths.
// Otherwise the list can overflow the container!
var linkSpacing = Math.floor((containerWidth - linksWidth) / (count - 1));
$children
.css('margin-right', linkSpacing + "px")
.filter(":last")
.css({"margin-right":0,"float":"right"})
.prev()
.css({"margin-right":0});
});
};
})(jQuery);
#nav {
text-align: justify;
min-width: 500px;
}
#nav:after {
content: '';
display: inline-block;
width: 100%;
}
#nav li {
display: inline-block;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment