Flexible navigation with javascript fallback
HTML
<div class="wrapper">
<p>Trying to make a navigation that fills the available space whilst keeping variable width buttons</p>
<p>Needs to work reliably in all modern browsers (ie7+, chrome, firefox etc)</p>
<p><strong>Notice</strong> there are two separate nav lists - this works with any number of buttons</p>
<div class="sizer"></div>
<nav>
<ul>
<li><a href="#" class="button">Multiplayer</a></li>
<li><a href="#" class="button">Action</a></li>
<li><a href="#" class="button">Platform</a></li>
<li><a href="#" class="button">Motorsports</a></li>
<li><a href="#" class="button">3D</a></li>
<li><a href="#" class="button">Sports</a></li>
<li><a href="#" class="button">Motorsports</a></li>
<li><a href="#" class="button">3D</a></li>
<li><a href="#" class="button">Sports</a></li>
</ul>
</nav>
<nav>
<ul>
<li><a href="#" class="button">Platform</a></li>
<li><a href="#" class="button">Motorsports</a></li>
<li><a href="#" class="button">3D</a></li>
<li><a href="#" class="button">Sports</a></li>
</ul>
</nav>
</div>
CSS
* {
margin:0;
padding:0;
}
body, html
{
font:12px tahoma;
background:#eee;
}
p {
margin:0 0 10px 0;
}
strong {
font-weight:bold;
}
nav {
height:50px;
}
nav li {
list-style-type:none;
float:left;
margin-right:5px;
}
.wrapper {
width:960px;
background:#fff;
display:block;
height:250px;
padding:20px;
}
.sizer {
display:block;
padding:5px;
background:#000;
margin:0 0 20px 0;
}
.button
{
font-weight:bold;
display: inline-block;
white-space: nowrap;
background-color: #ccc;
border: 1px solid #bbb;
padding: 0 9px;
text-decoration: none;
color: #036;
text-shadow: 0 1px 0 rgba(255,255,255,.8);
border-radius: 5px;
line-height:28px;
}
.button:hover
{
background-color: #ddd;
}
JavaScript
$(function() {
$('nav').each(function() {
width = 0;
var navItems = $(this).find('li');
$(this).find('li:last').css('margin-right', 0);
navItems.each (function () {
width = width + $(this).outerWidth(true);
});
// the 9 is the existing right padding
extra = Math.floor(($(this).width() - width) / navItems.length) + 9;
navItems.each(function () {
$(this).find('a').css('padding-right', extra);
});
});
});