Here's what I've got so far: fiddle
2 problems with it though:
- I've hard-coded the width of each
li
to 33%
, which I'd prefer not to do so that I can easily add more items.
- I want to put some spacing between each item (a gap in the background color), but as soon as I add a margin, one item will be bumped down a line. How do I get around that?
#main-nav {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
overflow: auto;
}
#main-nav li {
float: left;
width: 33%;
height: 25px;
text-align: center;
}
#main-nav li a {
width: 100%;
display: block;
height: 100%;
line-height: 25px;
text-decoration: none;
background-color: #e0e0f0;
font-weight: bold;
color: #021020;
}
#main-nav li a:hover {
background-color: #498cd5;
color: #ddeeee;
}
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
</ul>
See: http://jsfiddle.net/f6qmm/
display: table
is being used to evenly space a dynamic number of li
s. Unfortunately, that doesn't work in IE7, so *float: left
is used (for only IE7 and lower) so that at least they're all on one line - though it still looks horrendous.
padding-left: 5px
is applied to every li
, then li:first-child { padding-left: 0 }
removes it for only the first li
.
#main-nav {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
display: table;
table-layout: fixed;
overflow: hidden
}
#main-nav li {
display: table-cell;
*float: left; /* improve IE7 */
height: 25px;
text-align: center;
padding-left: 5px
}
#main-nav li:first-child {
padding-left: 0
}
#main-nav li a {
width: 100%;
display: block;
height: 100%;
line-height: 25px;
text-decoration: none;
background-color: #e0e0f0;
font-weight: bold;
color: #021020;
}
#main-nav li a:hover {
background-color: #498cd5;
color: #ddeeee;
}
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
</ul>
<hr />
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
<li><a href="#">four</a></li>
<li><a href="#">five</a></li>
</ul>
Try this fiddle: http://jsfiddle.net/Nk2Wy/1/.
This approach allows you adding an arbitrary number of items. If they do not fit on the line anymore, because they are so many or because the browser window is quite small, they are shown on further lines.
If you add a width: 50px
to the a
style, all those items have the same width. Right now, the width depends on the actual text.
See the question (and answers) How to get rid of white space between css horizontal list items? as well.
Due to this, I updated the fiddle once again: http://jsfiddle.net/Nk2Wy/3/.