How to keep <li> elements on single line in fixed width <ul>?

RubenGeert picture RubenGeert · Aug 22, 2013 · Viewed 41.2k times · Source

I've a header div and a menu ul below it. I'd like to accomplish 2 things:

1) the ul should have the same width as the div (outer vertical borders exactly same x position 2) I'd like to keep the spacing between li elements roughly equal

With some trial and error on the li's margins and padding I roughly achieved the first point in Google Chrome (please see this jsfiddle) but in Firefox the li's don't fit in the ul so they don't stay on a single line. Also, the last li tends to 'spill over' to a second line when zooming in/out.

I tried it with margin:5px auto and padding:5px auto on the li elements but here auto seems to mean zero.

Is this really difficult/impossible or am I overlooking something obvious?

I also tried width:fit-contents but that didn't help either.

Answer

LinkinTED picture LinkinTED · Aug 22, 2013

I edited a whole lot in your CSS, check the updated fiddle.

Basicly, this is what I've done:

HTML:

<ul>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a></li>
</ul>

CSS:

ul {
    width: 960px;
    display: table;
    table-layout: fixed;
}
ul li {
    display: table-cell;
}
ul li a {
    display: block;
}

The ul is displayed as a table, with the li's as table-cells, making it as width as the header. Within the li i display the anchors as a block, making them fill the whole li. Hope it suits you.

P.s. make sure you remove the class cf from the ul when you use this.